-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
327 lines (278 loc) · 8.92 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
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
package main
import (
"context"
"flag"
"fmt"
"hash/fnv"
"os"
"os/exec"
"sort"
"time"
"github.com/google/go-github/v37/github"
)
type hotfixPrs struct {
prs []*wrappedPullRequest
allCommits map[uint32]*commitMatch
}
type wrappedPullRequest struct {
pr *github.PullRequest
commits map[uint32]*commitMatch // TODO rename hashToCommits
head *commitMatch
tail *commitMatch
}
type commitMatch struct {
prCommit wrappedCommit
mainCommit wrappedCommit
previous *commitMatch
next *commitMatch
}
type wrappedCommit struct {
commit *github.RepositoryCommit
}
// hash creates a hash value to easily identify a commit
// The hash value is based on the commit msg and its creation date.
// Commit SHAs can't be used as they change after rebase&merge of the PR is done
func (c wrappedCommit) hash() uint32 {
v := c.commit.GetCommit()
h := fnv.New32a()
h.Write([]byte(v.GetMessage()))
if v.GetAuthor() != nil {
// For Author the date should be the same for the commit of the PR and for the commit within main branch
// For Commiter the date will be different as rebase&merge created a commit
h.Write([]byte(fmt.Sprintf("%v", v.GetAuthor().GetDate())))
} else {
// problematic in case of duplicate commit messages
fmt.Sprintf("WARN: no commitAuthor field. hash will only be generated from commit msg")
}
return h.Sum32()
}
func main() {
mbUsage := "main branch where to cherry pick from"
rbUsage := "release branch to add the hotfix to"
hUsage := "name of the hotfix"
prsUsage := "comma-separated list of PRs, e.g: '42,164'"
var mainBranch string
var releaseBranch string
var hotfixName string
var pullRequests string
flag.StringVar(&mainBranch, "mainBranch", "master", mbUsage)
flag.StringVar(&mainBranch, "mb", "master", mbUsage)
flag.StringVar(&releaseBranch, "releaseBranch", "", rbUsage)
flag.StringVar(&releaseBranch, "rb", "", rbUsage)
flag.StringVar(&hotfixName, "hotfix", "", hUsage)
flag.StringVar(&hotfixName, "hf", "", hUsage)
flag.StringVar(&pullRequests, "pullRequests", "", prsUsage)
flag.StringVar(&pullRequests, "prs", "", prsUsage)
flag.Parse()
if releaseBranch == "" {
fmt.Print("parameter 'releaseBranch' can't be empty")
os.Exit(1)
}
if hotfixName == "" {
fmt.Print("parameter 'hotfixName' can't be empty")
os.Exit(1)
}
if pullRequests == "" {
fmt.Print("parameter 'pullRequests' can't be empty")
os.Exit(1)
}
token := getGitHubToken()
if token == "" {
fmt.Print("Error: GITHUB_TOKEN environment variable is not set")
os.Exit(1)
}
repoInfo, err := getActiveRepoInfo()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Repository: %s\\%s\n", repoInfo.Owner, repoInfo.Name)
fmt.Printf("Creating hotfix %s based on %s.\n", hotfixName, releaseBranch)
fmt.Printf("Cherry-Picking commits of PRs '%s' from branch '%s'\n", pullRequests, mainBranch)
ctx := context.Background()
client := newGitHubApiClient(repoInfo.Owner.Login, repoInfo.Name, token, ctx)
hotfixPrs, err := client.getMergedPullRequests(pullRequests)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if len(hotfixPrs.prs) == 0 {
fmt.Println("Empty PR List")
os.Exit(1)
}
err = client.collectCommitsFromPRs(hotfixPrs)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
// fetch commits from main branch
mainBranchCommits, err := client.fetchCommits(mainBranch, hotfixPrs.getOldestPRCreationDate())
if err != nil {
fmt.Printf("Failed to list commits: %v\n", err)
os.Exit(1)
}
err = matchCommits(mainBranchCommits, hotfixPrs.allCommits)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
// TODO maybe move sorting of the commits into cherryPickMatchingCommits
// sort commits after order of the main branch to avoid merge-conflicts later
err = hotfixPrs.sortMatchingCommits()
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
for _, pr := range hotfixPrs.prs {
fmt.Printf("PR %d (merged at: %v)\n", *(pr.pr.Number), pr.pr.MergedAt)
fmt.Printf("\thead commitSHA: %v\n", pr.head.prCommit.commit.GetSHA())
cm := pr.head
for cm != nil {
fmt.Printf("\t\tmainCommitSHA: %v; prCommitSHA: %v\n", cm.mainCommit.commit.GetSHA(), cm.prCommit.commit.GetSHA())
cm = cm.next
}
}
// checkout hotfix branch based on the release branch
err = checkoutHotfixBranch(releaseBranch, hotfixName)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
// cherry-pick commits to hotfix branch
err = cherryPickMatchingCommits(hotfixPrs)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
// push hotfix branch
err = pushBranch(hotfixName)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
prBody := createPullRequestBody(hotfixPrs)
// open PR for hotfix and add a nice summary of the included PRs
pr, err := client.openPullRequest(fillOutPullRequestFields(hotfixName, releaseBranch, prBody))
if err != nil {
fmt.Printf("error creating pull request: %v\n", err)
os.Exit(1)
}
fmt.Printf("Successfully created PR: %s\n\n", pr.GetHTMLURL())
}
// sortMatchingCommits sorts commits after the order of the main branch
func (hprs hotfixPrs) sortMatchingCommits() error {
// sort by wrappedPullRequests by MergedDate
sort.Slice(hprs.prs, func(i, j int) bool {
return hprs.prs[i].pr.MergedAt.Before(*(hprs.prs[j].pr.MergedAt))
})
return nil
}
// pushBranch pushes changes of branch to origin
func pushBranch(branchName string) error {
err := executeGitCmd("push", "origin", branchName)
if err != nil {
return err
}
return nil
}
// cherryPickMatchingCommits cherry-picks matching commits from main branch to current branch
func cherryPickMatchingCommits(hPrs *hotfixPrs) error {
for _, pr := range hPrs.prs {
fmt.Printf("cherry pick PR %d (merged at: %v)\n", *(pr.pr.Number), pr.pr.MergedAt)
cm := pr.head // start with the oldest commit
for cm != nil {
commitSHA := cm.mainCommit.commit.GetSHA()
// fmt.Printf("PR %d (cherry pick commitSHA: %v)\n", *(pr.pr.Number), commitSHA)
err := executeGitCmd("cherry-pick", commitSHA)
if err != nil {
return err
}
// fmt.Printf("PR %d (next commit: %v)\n", *(pr.pr.Number), cm.next)
cm = cm.next
}
}
return nil
}
// fillOutPullRequestFields fills out the necessary fields of a GitHub pull request
func fillOutPullRequestFields(hotfixName string, releaseBranch string, prBody string) *github.NewPullRequest {
return &github.NewPullRequest{
Title: github.String(fmt.Sprintf("Hotfix %v", hotfixName)),
Head: github.String(hotfixName),
Base: github.String(releaseBranch),
Body: github.String(prBody),
}
}
// createPullRequestBody creates markdown table for the PR body
func createPullRequestBody(hPrs *hotfixPrs) string {
body := "Pull Request | commit main branch | commit pr \n" +
"------------ | ------------- | ------------- \n"
for _, wrappedPr := range hPrs.prs {
cm := wrappedPr.head
for cm != nil {
body = body + wrappedPr.pr.GetHTMLURL() + " | " + cm.mainCommit.commit.GetHTMLURL() + " | " + cm.prCommit.commit.GetHTMLURL() + " \n"
cm = cm.next
}
}
return body
}
// checkoutHotfixBranch checks out a new hotfix branch based on an existing release branch
func checkoutHotfixBranch(releaseBranch, hotfixName string) error {
err := executeGitCmd("fetch")
if err != nil {
return err
}
err = executeGitCmd("checkout", releaseBranch)
if err != nil {
return err
}
err = executeGitCmd("pull")
if err != nil {
return err
}
// force switching branch. if branch name already exists branch head will be reset
err = executeGitCmd("switch", "--force-create", hotfixName)
if err != nil {
return err
}
return nil
}
func executeGitCmd(args ...string) error {
gitPull := exec.Command("git", args...)
out, err := gitPull.Output()
if err != nil {
return fmt.Errorf("error during 'git %v': %v\n%s\n", args, err, out)
} else {
fmt.Printf("%s\n%s\n", gitPull.String(), out)
}
return nil
}
// matchCommits matches commits from main branch with commits from the PRs
// Two commit match if their hash value is equal.
func matchCommits(mainBranchCommits []*github.RepositoryCommit, allPrCommits map[uint32]*commitMatch) error {
var matchingCommits []*commitMatch
for _, commit := range mainBranchCommits {
wrappedMainBranchCommit := wrappedCommit{commit: commit}
commitMatch, ok := allPrCommits[wrappedMainBranchCommit.hash()]
if ok {
commitMatch.mainCommit = wrappedMainBranchCommit
matchingCommits = append(matchingCommits, commitMatch)
}
}
// verify all the pr commits have a corresponding main branch commit linked
if len(allPrCommits) != len(matchingCommits) {
// TODO print all commits that have no mainBranchCommit
return fmt.Errorf("some commits could not be matched")
}
return nil
}
// getOldestPRCreationDate returns date of the PR which was created before all other PRs
func (hprs *hotfixPrs) getOldestPRCreationDate() time.Time {
oldest := time.Now()
for _, pr := range hprs.prs {
prCreationDate := *(pr.pr.CreatedAt)
if oldest.After(prCreationDate) { // TODO check if it works for different time zones, too
oldest = prCreationDate
}
}
return oldest
}