This repository has been archived by the owner on Feb 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmerge_and_label.go
335 lines (287 loc) · 8.99 KB
/
merge_and_label.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
package chlog
import (
"encoding/base64"
"errors"
"fmt"
"log"
"os"
"regexp"
"strings"
"sync"
"github.com/google/go-github/github"
"github.com/parkr/auto-reply/auth"
"github.com/parkr/auto-reply/ctx"
"github.com/parkr/changelog"
)
// changelogCategory is a changelog category, like "Site Enhancements" and such.
type changelogCategory struct {
Prefix, Slug, Section string
Labels []string
}
var (
mergeCommentRegexp = regexp.MustCompile("@[a-zA-Z-_]+: (merge|:shipit:|:ship:)( \\+([a-zA-Z-_ ]+))?")
mergeOptions = &github.PullRequestOptions{Squash: false}
categories = []changelogCategory{
changelogCategory{
Prefix: "major",
Slug: "major-enhancements",
Section: "Major Enhancements",
Labels: []string{"feature"},
},
changelogCategory{
Prefix: "minor",
Slug: "minor-enhancements",
Section: "Minor Enhancements",
Labels: []string{"enhancement"},
},
changelogCategory{
Prefix: "bug",
Slug: "bug-fixes",
Section: "Bug Fixes",
Labels: []string{"bug", "fix"},
},
changelogCategory{
Prefix: "dev",
Slug: "development-fixes",
Section: "Development Fixes",
Labels: []string{"internal", "fix"},
},
changelogCategory{
Prefix: "doc",
Slug: "documentation",
Section: "Documentation",
Labels: []string{"documentation"},
},
changelogCategory{
Prefix: "port",
Slug: "forward-ports",
Section: "Forward Ports",
Labels: []string{"forward-port"},
},
changelogCategory{
Prefix: "site",
Slug: "site-enhancements",
Section: "Site Enhancements",
Labels: []string{"documentation"},
},
}
)
func MergeAndLabel(context *ctx.Context, payload interface{}) error {
event, ok := payload.(*github.IssueCommentEvent)
if !ok {
return context.NewError("MergeAndLabel: not an issue comment event")
}
// Is this a pull request?
if event.Issue == nil || event.Issue.PullRequestLinks == nil {
return context.NewError("MergeAndLabel: not a pull request")
}
var changeSectionLabel string
isReq, labelFromComment := parseMergeRequestComment(*event.Comment.Body)
// Is It a merge request comment?
if !isReq {
return context.NewError("MergeAndLabel: not a merge request comment")
}
if os.Getenv("AUTO_REPLY_DEBUG") == "true" {
log.Println("MergeAndLabel: received event:", event)
}
var wg sync.WaitGroup
owner, repo, number := *event.Repo.Owner.Login, *event.Repo.Name, *event.Issue.Number
ref := fmt.Sprintf("%s/%s#%d", owner, repo, number)
// Does the user have merge/label abilities?
if !auth.CommenterHasPushAccess(context, *event) {
log.Printf("%s isn't authenticated to merge anything on %s", *event.Comment.User.Login, *event.Repo.FullName)
return errors.New("commenter isn't allowed to merge")
}
// Should it be labeled?
if labelFromComment != "" {
changeSectionLabel = sectionForLabel(labelFromComment)
} else {
changeSectionLabel = "none"
}
fmt.Printf("changeSectionLabel = '%s'\n", changeSectionLabel)
// Merge
commitMsg := fmt.Sprintf("Merge pull request %v", number)
_, _, mergeErr := context.GitHub.PullRequests.Merge(owner, repo, number, commitMsg, mergeOptions)
if mergeErr != nil {
return context.NewError("MergeAndLabel: error merging %s: %v", ref, mergeErr)
}
// Delete branch
repoInfo, _, getRepoErr := context.GitHub.PullRequests.Get(owner, repo, number)
if getRepoErr != nil {
return context.NewError("MergeAndLabel: error getting PR info %s: %v", ref, getRepoErr)
}
if repoInfo == nil {
return context.NewError("MergeAndLabel: tried to get PR, but couldn't. repoInfo was nil.")
}
// Delete branch
if deletableRef(repoInfo, owner) {
wg.Add(1)
go func() {
ref := fmt.Sprintf("heads/%s", *repoInfo.Head.Ref)
_, deleteBranchErr := context.GitHub.Git.DeleteRef(owner, repo, ref)
if deleteBranchErr != nil {
fmt.Printf("MergeAndLabel: error deleting branch %v\n", mergeErr)
}
wg.Done()
}()
}
wg.Add(1)
go func() {
err := addLabelsForSubsection(context, owner, repo, number, changeSectionLabel)
if err != nil {
fmt.Printf("MergeAndLabel: error applying labels: %v\n", err)
}
wg.Done()
}()
wg.Add(1)
go func() {
// Read History.markdown, add line to appropriate change section
historyFileContents, historySHA := getHistoryContents(context, owner, repo)
// Add merge reference to history
newHistoryFileContents := addMergeReference(historyFileContents, changeSectionLabel, *repoInfo.Title, number)
// Commit change to History.markdown
commitErr := commitHistoryFile(context, historySHA, owner, repo, number, newHistoryFileContents)
if commitErr != nil {
fmt.Printf("comments: error committing updated history %v\n", mergeErr)
}
wg.Done()
}()
wg.Wait()
return nil
}
func parseMergeRequestComment(commentBody string) (bool, string) {
matches := mergeCommentRegexp.FindAllStringSubmatch(commentBody, -1)
if matches == nil || matches[0] == nil {
return false, ""
}
var label string
if len(matches[0]) >= 4 {
if labelFromComment := matches[0][3]; labelFromComment != "" {
label = downcaseAndHyphenize(labelFromComment)
}
}
return true, normalizeLabel(label)
}
func downcaseAndHyphenize(label string) string {
return strings.Replace(strings.ToLower(label), " ", "-", -1)
}
func normalizeLabel(label string) string {
for _, category := range categories {
if strings.HasPrefix(label, category.Prefix) {
return category.Slug
}
}
return label
}
func sectionForLabel(slug string) string {
for _, category := range categories {
if slug == category.Slug {
return category.Section
}
}
return slug
}
func labelsForSubsection(changeSectionLabel string) []string {
for _, category := range categories {
if changeSectionLabel == category.Section {
return category.Labels
}
}
return []string{}
}
func selectSectionLabel(labels []github.Label) string {
for _, label := range labels {
if sectionForLabel(*label.Name) != *label.Name {
return *label.Name
}
}
return ""
}
func containsChangeLabel(commentBody string) bool {
_, labelFromComment := parseMergeRequestComment(commentBody)
return labelFromComment != ""
}
func addLabelsForSubsection(context *ctx.Context, owner, repo string, number int, changeSectionLabel string) error {
labels := labelsForSubsection(changeSectionLabel)
if len(labels) < 1 {
return fmt.Errorf("no labels for changeSectionLabel='%s'", changeSectionLabel)
}
_, _, err := context.GitHub.Issues.AddLabelsToIssue(owner, repo, number, labels)
return err
}
func getHistoryContents(context *ctx.Context, owner, repo string) (content, sha string) {
contents, _, _, err := context.GitHub.Repositories.GetContents(
owner,
repo,
"History.markdown",
&github.RepositoryContentGetOptions{Ref: "heads/master"},
)
if err != nil {
fmt.Printf("comments: error getting History.markdown %v\n", err)
return "", ""
}
return base64Decode(*contents.Content), *contents.SHA
}
func base64Decode(encoded string) string {
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
fmt.Printf("comments: error decoding string: %v\n", err)
return ""
}
return string(decoded)
}
func parseChangelog(historyFileContents string) (*changelog.Changelog, error) {
changes, err := changelog.NewChangelogFromReader(strings.NewReader(historyFileContents))
if historyFileContents == "" {
err = nil
changes = changelog.NewChangelog()
}
return changes, err
}
func addMergeReference(historyFileContents, changeSectionLabel, prTitle string, number int) string {
changes, err := parseChangelog(historyFileContents)
if err != nil {
fmt.Printf("comments: error %v\n", err)
return historyFileContents
}
changeLine := &changelog.ChangeLine{
Summary: prTitle,
Reference: fmt.Sprintf("#%d", number),
}
// Put either directly in the version history or in a subsection.
if changeSectionLabel == "none" {
changes.AddLineToVersion("HEAD", changeLine)
} else {
changes.AddLineToSubsection("HEAD", changeSectionLabel, changeLine)
}
return changes.String()
}
func deletableRef(pr *github.PullRequest, owner string) bool {
return pr != nil &&
pr.Head != nil &&
pr.Head.Repo != nil &&
pr.Head.Repo.Owner != nil &&
pr.Head.Repo.Owner.Login != nil &&
*pr.Head.Repo.Owner.Login == owner &&
pr.Head.Ref != nil &&
*pr.Head.Ref != "master" &&
*pr.Head.Ref != "gh-pages"
}
func commitHistoryFile(context *ctx.Context, historySHA, owner, repo string, number int, newHistoryFileContents string) error {
repositoryContentsOptions := &github.RepositoryContentFileOptions{
Message: github.String(fmt.Sprintf("Update history to reflect merge of #%d [ci skip]", number)),
Content: []byte(newHistoryFileContents),
SHA: github.String(historySHA),
Committer: &github.CommitAuthor{
Name: github.String("jekyllbot"),
Email: github.String("[email protected]"),
},
}
updateResponse, _, err := context.GitHub.Repositories.UpdateFile(owner, repo, "History.markdown", repositoryContentsOptions)
if err != nil {
fmt.Printf("comments: error committing History.markdown: %v\n", err)
return err
}
fmt.Printf("comments: updateResponse: %s\n", updateResponse)
return nil
}