-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
261 lines (210 loc) · 6.28 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package main
import (
"flag"
"fmt"
"io"
"os"
"sync"
"text/tabwriter"
"time"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
gitlab "github.com/xanzy/go-gitlab"
)
var (
token string
gitlabURL string
groups []string
fromDate time.Time
untilDate time.Time
)
func main() {
setConfig()
logrus.Infof("Looking for MRs between %s and %s...", fromDate.Format("2006-01-02"), untilDate.Format("2006-01-02"))
//Init Gitlab client
git := gitlab.NewClient(nil, token)
if err := git.SetBaseURL(gitlabURL); err != nil {
logrus.Fatalf("Error when setting gitlab base URL : %s", err.Error())
}
print(findMergeRequest(git, groups, fromDate, untilDate))
}
//setUpLogs set on writer as output for the logs and set up the level
func setUpLogs(out io.Writer, level string) error {
logrus.SetOutput(out)
lvl, err := logrus.ParseLevel(level)
if err != nil {
return err
}
logrus.SetLevel(lvl)
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
})
return nil
}
func setConfig() {
viper.SetConfigName(".mergedlistr")
viper.AddConfigPath("$HOME/")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
logrus.Fatalf("fatal error config file: %s", err)
}
token = viper.GetString("gitlab-token")
gitlabURL = viper.GetString("gitlab-url")
groups = viper.GetStringSlice("groups")
//var duration time.Duration
var fDate string
var tDate string
var verbosity string
flag.StringVar(&fDate, "f", time.Now().AddDate(0, 0, -1).Format("2006-01-02") , `From date to look for merged PRs. Format is : "-f YYYY-MM-DD"`)
flag.StringVar(&tDate, "t", time.Now().Format("2006-01-02") , `To date to look for merged PRs. Format is : "-t YYYY-MM-DD"`)
flag.StringVar(&verbosity, "v", logrus.InfoLevel.String(), "Log level (debug, info, warn, error, fatal, panic")
flag.Parse()
fromDate, _ = time.Parse("2006-01-02", fDate)
untilDate, _ = time.Parse("2006-01-02", tDate)
untilDate = untilDate.AddDate(0, 0, 1)
if err := setUpLogs(os.Stdout, verbosity); err != nil {
logrus.Fatal(err.Error())
}
}
func print(mergeRequestByProject map[string][]map[string]string) {
//Init writer
w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 8, 0, '\t', 0)
fmt.Fprintln(w, "Project\tMerge Request\tDate\tAuthor")
for p, mrs := range mergeRequestByProject {
for _, mr := range mrs {
fmt.Fprintf(w, fmt.Sprintf("%s\t%s\t%s\t%s", p, mr["title"], mr["mergedAt"], mr["createdBy"]))
fmt.Fprintln(w)
}
}
fmt.Fprintln(w)
w.Flush()
}
func getGroups(git *gitlab.Client, groupToWatch []string) []*gitlab.Group {
var wgg sync.WaitGroup
mu := &sync.Mutex{}
var groups []*gitlab.Group
//Get groups to watch
for _, gtg := range groupToWatch {
wgg.Add(1)
go func(gtg string) {
gs, _, err := git.Groups.ListGroups(&gitlab.ListGroupsOptions{
Search: gitlab.String(gtg),
})
if err != nil {
logrus.Fatal(err)
}
for _, g := range gs {
logrus.Debugf("Found group : %s", g.Name)
}
mu.Lock()
groups = append(groups, gs...)
mu.Unlock()
wgg.Done()
}(gtg)
}
wgg.Wait()
return groups
}
func getProjects(git *gitlab.Client, groups []*gitlab.Group) []*gitlab.Project{
var wgp sync.WaitGroup
mu := &sync.Mutex{}
var projects []*gitlab.Project
for _, g := range groups {
wgp.Add(1)
go func(g *gitlab.Group) {
archived := false
//Find all projects
ps, _, err := git.Groups.ListGroupProjects(g.ID, &gitlab.ListGroupProjectsOptions{
//Since we want to avoid recurring across paginated results, we set the pagination very high
ListOptions: gitlab.ListOptions{
Page: 1,
PerPage: 300,
},
Archived: &archived,
})
if err != nil {
logrus.Fatal(err)
}
for _, p := range ps {
logrus.Debugf("Found project %s in group %s", p.Name, g.Name)
}
mu.Lock()
projects = append(projects, ps...)
mu.Unlock()
wgp.Done()
}(g)
}
wgp.Wait()
return projects
}
func getMergeRequests(git *gitlab.Client, projects []*gitlab.Project, from, to time.Time) []*gitlab.MergeRequest {
var wgmr sync.WaitGroup
mu := &sync.Mutex{}
var mergeRequests []*gitlab.MergeRequest
//We look for the from date minus 1 day because we gitlab does not offers th ability to filter on Merged At field.
//But since merging is considered as an update, we prefer to take a little bit too large and filter on the merge date after.
firstUpdatedDate := from.AddDate(0, 0, -1)
lastUpdatedDate := to.AddDate(0, 0, 1)
for _, p := range projects {
wgmr.Add(1)
go func(p *gitlab.Project) {
defer wgmr.Done()
logrus.Debugf("Looking for merge request in project : %s", p.Name)
mrs, _, err := git.MergeRequests.ListProjectMergeRequests(p.ID, &gitlab.ListProjectMergeRequestsOptions{
ListOptions: gitlab.ListOptions{
Page: 1,
PerPage: 300,
},
State: gitlab.String("merged"),
OrderBy: gitlab.String("updated_at"),
Scope: gitlab.String("all"),
UpdatedAfter: &firstUpdatedDate,
UpdatedBefore: &lastUpdatedDate,
})
if err != nil {
logrus.Fatal(err)
}
logrus.Debugf("Found %d MR in project %s", len(mrs), p.Name)
for _, mr := range mrs {
logrus.Debugf("Found Merge Request %d titled %s on project %s", mr.ID, mr.Title, p.Name)
}
mu.Lock()
mergeRequests = append(mergeRequests, mrs...)
mu.Unlock()
}(p)
}
wgmr.Wait()
return mergeRequests
}
func getProjectName(ID int, projects []*gitlab.Project) string {
for _, p := range projects {
if p.ID == ID {
return p.Name
}
}
return "Unknown Project"
}
func findMergeRequest(git *gitlab.Client, groupToWatch []string, from, to time.Time) map[string][]map[string]string {
results := make(map[string][]map[string]string, 500)
groups := getGroups(git, groupToWatch)
logrus.Debugf("Found %d groups", len(groups))
projects := getProjects(git, groups)
logrus.Debugf("Found %d projects", len(projects))
mergeRequests := getMergeRequests(git, projects, from, to)
for _, mr := range mergeRequests {
if mr.MergedAt.After(from) && mr.MergedAt.Before(to) {
mr := map[string]string{
"projectName": getProjectName(mr.ProjectID, projects),
"title": mr.Title,
"mergedAt": mr.MergedAt.Format(time.RFC3339),
"createdBy": mr.Author.Name,
"link": mr.WebURL,
}
results[mr["projectName"]] = append(results[mr["projectName"]], mr)
}
}
return results
}