-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitlab.go
378 lines (327 loc) · 10.3 KB
/
gitlab.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package main
import (
log "github.com/sirupsen/logrus"
"github.com/xanzy/go-gitlab"
)
var client *gitlab.Client
func init() {
var err error
client, err = gitlab.NewClient(config.GitLab.AccessToken, gitlab.WithBaseURL(config.GitLab.Url))
if err != nil {
log.Panicln("failed to init gitlab client")
}
}
func getEffectiveProjects() []*gitlab.Project {
var projects = []*gitlab.Project{}
configProjects := config.GitLab.Projects
if len(configProjects) > 0 {
for _, p := range configProjects {
log := log.WithFields(log.Fields{"projectID": p.ID, "projectPath": p.Path})
project, _, err := client.Projects.GetProject(p.ID, nil)
if err != nil {
log.Panicln("failed to get project info")
}
user, _, err := client.Users.CurrentUser()
if err != nil {
log.Panicln("failed to get user info")
}
if !isUserProjectMaintainer(user.ID, project.ID) {
log.Errorln("current user is not the maintainer of project")
}
projects = append(projects, project)
}
} else {
return listMaintainedProjects()
}
return projects
}
func listMaintainedProjects() []*gitlab.Project {
var maintainedProjects = []*gitlab.Project{}
user, _, err := client.Users.CurrentUser()
if err != nil {
log.Panicln("failed to get user info")
}
projects := listAllProjects()
for _, p := range projects {
if isUserProjectMaintainer(user.ID, p.ID) {
maintainedProjects = append(maintainedProjects, p)
}
}
return maintainedProjects
}
func isUserProjectMaintainer(userID int, projectID int) bool {
maintainers := listProjectMaintainers(projectID)
for _, m := range maintainers {
if userID == m.ID {
return true
}
}
return false
}
func listAllProjects() []*gitlab.Project {
var (
projects = []*gitlab.Project{}
options = &gitlab.ListProjectsOptions{Archived: gitlab.Bool(false)}
)
for {
projs, resp, err := client.Projects.ListProjects(options)
if err != nil {
log.Errorln("failed to get project list")
}
projects = append(projects, projs...)
if resp.NextPage == 0 {
break
}
options.Page = resp.NextPage
}
return projects
}
func processProjectMergeRequests(project *gitlab.Project) {
var (
mergeRequestNeedRebase []*gitlab.MergeRequest
mergeRequestRunningPipeline []*gitlab.MergeRequest
)
mergeRequests := listProjectMergeRequests(project.ID)
log.WithField("project", project.Path).Infoln("pending merge request count", len(mergeRequests))
branchMergeRequests := make(map[string][]*gitlab.MergeRequest)
branchMergerIDs := make(map[string]MergerIDSet)
for _, mr := range mergeRequests {
branchMergeRequests[mr.TargetBranch] = append(branchMergeRequests[mr.TargetBranch], mr)
branchMergerIDs[mr.TargetBranch] = listEligibleMergers(project.ID, mr.TargetBranch)
}
for _, mr := range mergeRequests {
log := log.WithFields(log.Fields{
"project": project.Path,
"title": mr.Title,
"id": mr.ID,
})
// because projectMergeRequest lacks some fields
mergeRequest, _, err := client.MergeRequests.GetMergeRequest(project.ID, mr.IID, nil)
if err != nil {
log.WithField("mergeRequest", mr.IID).Errorln("failed to get merge request info")
}
// the order of the following checks matters
if !isMergeRequestReady(mergeRequest) {
log.Debugln("merge request is not ready")
continue
}
if !isMergeRequestApproved(mergeRequest, project.ID, branchMergerIDs[mr.TargetBranch]) {
log.Debugln("merge request not be appproved")
continue
}
if isMergeRequestPipelineFailed(mergeRequest) {
log.Debugln("merge request does not success")
continue
}
if isMergeRequestNeedRebase(mergeRequest, project.ID) {
log.Debugln("merge request needs rebase")
mergeRequestNeedRebase = append(mergeRequestNeedRebase, mergeRequest)
continue
}
opts := gitlab.AcceptMergeRequestOptions{
Squash: gitlab.Bool(true),
MergeWhenPipelineSucceeds: gitlab.Bool(true),
}
if isMergeRequestPipelineRunning(mergeRequest) {
log.Infoln("set to merge when pipeline become success")
client.MergeRequests.AcceptMergeRequest(project.ID, mergeRequest.IID, &opts)
mergeRequestRunningPipeline = append(mergeRequestRunningPipeline, mergeRequest)
continue
}
log.Infoln("merging")
client.MergeRequests.AcceptMergeRequest(project.ID, mergeRequest.IID, &opts)
return
}
// rebase merge request only if there are no merge requests running pipeline
// otherwise rebasing is a waste of runner resource
if len(mergeRequestRunningPipeline) == 0 {
// here we rebase all merge requests and see which will get merged firstly
// shoud make a smarter algorithm
for _, mergeRequest := range mergeRequestNeedRebase {
if isMergeRequestNeedResolveConflicts(mergeRequest) {
continue
}
log.WithFields(log.Fields{
"projectID": project.ID,
"mergeRequest": mergeRequest.IID,
}).Infoln("rebasing")
client.MergeRequests.RebaseMergeRequest(project.ID, mergeRequest.IID)
}
}
}
func listEligibleMergers(projectID int, branch string) MergerIDSet {
var mergerIDSet = make(MergerIDSet)
for _, m := range listProjectMaintainers(projectID) {
mergerIDSet.Add(m.ID)
}
protectedBranch, resp, err := client.ProtectedBranches.GetProtectedBranch(projectID, branch)
if err != nil {
// not protected branch
// TODO: improve
if resp.StatusCode == 404 {
for _, m := range append(listProjectMaintainers(projectID), listProjectDevelopers(projectID)...) {
mergerIDSet.Add(m.ID)
}
return mergerIDSet
} else {
log.WithFields(log.Fields{
"projectID": projectID,
"branch": branch,
}).Errorln("failed to get projected branch info", err)
}
}
var branchAccessDescriptions []*gitlab.BranchAccessDescription
branchAccessDescriptions = append(branchAccessDescriptions, protectedBranch.MergeAccessLevels...)
branchAccessDescriptions = append(branchAccessDescriptions, protectedBranch.PushAccessLevels...)
for _, mal := range branchAccessDescriptions {
if mal.UserID != 0 {
mergerIDSet.Add(mal.UserID)
} else {
switch mal.AccessLevelDescription {
case "Maintainers":
{
// maintainers have been added above
continue
}
case "Developers + Maintainers":
{
for _, u := range listProjectDevelopers(projectID) {
mergerIDSet.Add(u.ID)
}
}
case "No one":
{
continue
}
default:
{
log.WithFields(log.Fields{
"projectID": projectID,
"branch": branch,
"accessLevel": mal.AccessLevel,
"accessLevelDescription": mal.AccessLevelDescription,
}).Warningln("unknown merge access level")
}
}
}
}
return mergerIDSet
}
func listProjectMaintainers(projectID int) []*gitlab.ProjectMember {
var (
maintainers []*gitlab.ProjectMember
options = &gitlab.ListProjectMembersOptions{}
)
for {
members, resp, err := client.ProjectMembers.ListAllProjectMembers(projectID, options)
if err != nil {
log.WithFields(log.Fields{"projectID": projectID}).Panicln("failed to get project members")
}
for _, member := range members {
// owner: 50
// maintainers: 40
if member.AccessLevel >= 40 {
maintainers = append(maintainers, member)
}
}
if resp.NextPage == 0 {
break
}
options.Page = resp.NextPage
}
return maintainers
}
func listProjectDevelopers(projectID int) []*gitlab.ProjectMember {
var (
developers []*gitlab.ProjectMember
options = &gitlab.ListProjectMembersOptions{}
)
for {
members, resp, err := client.ProjectMembers.ListAllProjectMembers(projectID, options)
if err != nil {
log.WithFields(log.Fields{"projectID": projectID}).Panicln("failed to get project members")
}
for _, member := range members {
if member.AccessLevel == 30 {
developers = append(developers, member)
}
}
if resp.NextPage == 0 {
break
}
options.Page = resp.NextPage
}
return developers
}
func listProjectMergeRequests(projectID int) []*gitlab.MergeRequest {
var (
mergeRequests = []*gitlab.MergeRequest{}
options = &gitlab.ListProjectMergeRequestsOptions{
State: gitlab.String("opened"),
Draft: gitlab.Bool(false),
WIP: gitlab.String("no"),
OrderBy: gitlab.String("created_at"),
Sort: gitlab.String("asc"),
}
)
for {
mrs, resp, err := client.MergeRequests.ListProjectMergeRequests(projectID, options)
if err != nil {
log.WithFields(log.Fields{"projectID": projectID}).Errorln("failed to get project merge requests")
}
mergeRequests = append(mergeRequests, mrs...)
if resp.NextPage == 0 {
break
}
options.Page = resp.NextPage
}
return mergeRequests
}
func isMergeRequestReady(mergeRequest *gitlab.MergeRequest) bool {
return !mergeRequest.WorkInProgress && !mergeRequest.Draft
}
func isMergeRequestNeedResolveConflicts(mergeRequest *gitlab.MergeRequest) bool {
return mergeRequest.HasConflicts
}
func isMergeRequestNeedRebase(mergeRequest *gitlab.MergeRequest, projectID int) bool {
var sourceBranchBaseSha = mergeRequest.DiffRefs.BaseSha
var targetBranchHeadSha = func() string {
branch, _, err := client.Branches.GetBranch(projectID, mergeRequest.TargetBranch)
if err != nil {
log.WithFields(log.Fields{
"projectID": projectID,
"branch": mergeRequest.TargetBranch,
}).Errorln("failed to get branch info")
}
return branch.Commit.ID
}()
return sourceBranchBaseSha != targetBranchHeadSha
}
func isMergeRequestPipelineSucceed(mergeRequest *gitlab.MergeRequest) bool {
status := mergeRequest.HeadPipeline.Status
return status == "success" || status == "skipped"
}
func isMergeRequestPipelineFailed(mergeRequest *gitlab.MergeRequest) bool {
status := mergeRequest.HeadPipeline.Status
return status == "failed" || status == "cancelled"
}
func isMergeRequestPipelineRunning(mergeRequest *gitlab.MergeRequest) bool {
return !isMergeRequestPipelineSucceed(mergeRequest) && !isMergeRequestPipelineFailed(mergeRequest)
}
func isMergeRequestApproved(mergeRequest *gitlab.MergeRequest, projectID int, mergers MergerIDSet) bool {
mergeRequestApprovals, _, err := client.MergeRequestApprovals.GetApprovalState(projectID, mergeRequest.IID, nil)
if err != nil {
log.WithFields(log.Fields{
"projectID": projectID,
"mergeRequest": mergeRequest.IID,
}).Errorln("failed to get merge request approval info")
}
for _, approvalRule := range mergeRequestApprovals.Rules {
for _, approver := range approvalRule.ApprovedBy {
if mergers.Has(approver.ID) {
return true
}
}
}
return false
}