forked from rnorth/gh-combine-prs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
220 lines (179 loc) · 5.56 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
package main
import (
"flag"
"fmt"
"hash/fnv"
"os"
"strings"
"github.com/cli/go-gh"
"github.com/cli/go-gh/pkg/api"
"github.com/cli/go-gh/pkg/repository"
)
var dryRunFlag bool
var helpFlag bool
var interactiveFlag bool
var limitFlag int
var queryFlag string
var skipPRCheckFlag bool
var verboseFlag bool
var ghClient api.RESTClient
var currentRepo repository.Repository
var extensionLogger Logger
const combinedPRsBranchName = "combined-pr-branch"
func init() {
flag.BoolVar(&dryRunFlag, "dry-run", false, "If set, will not actually merge the PRs, forcing verbose mode to show internal steps. Defaults to false when not specified")
flag.BoolVar(&helpFlag, "help", false, "Show help for multi-merge-prs")
flag.BoolVar(&interactiveFlag, "interactive", false, "Enable interactive mode. If set, will prompt for selecting the PRs to merge")
flag.IntVar(&limitFlag, "limit", 50, "Sets the maximum number of PRs that will be combined. Defaults to 50")
flag.StringVar(&queryFlag, "query", "", `sets the query used to find combinable PRs. e.g. --query "author:app/dependabot to combine Dependabot PRs`)
flag.BoolVar(&skipPRCheckFlag, "skip-pr-check", false, `if set, will combine matching PRs even if they are not passing checks. Defaults to false when not specified`)
flag.BoolVar(&verboseFlag, "verbose", false, `if set, will print verbose output. Defaults to false when not specified`)
}
func main() {
flag.Parse()
if dryRunFlag {
// force verbose mode when dry-running
verboseFlag = true
}
extensionLogger = newLogger(verboseFlag)
if helpFlag {
usage(0)
}
if queryFlag == "" {
usage(1, "ERROR: --query is required")
}
client, err := gh.RESTClient(nil)
if err != nil {
panic(err)
}
ghClient = client
repo, err := gh.CurrentRepository()
if err != nil {
panic(err)
}
fmt.Printf("Current repository is %s/%s\n", repo.Owner(), repo.Name())
currentRepo = repo
extensionLogger.Debugf("Dry-run mode: %t\n", dryRunFlag)
selectedPRs, err := fetchAndSelectPRs(interactiveFlag)
if err != nil {
extensionLogger.Errorf("while fetching the PRs. Exiting: %v\n", err)
os.Exit(1)
}
if len(selectedPRs) == 0 {
extensionLogger.Warnf("No PRs selected to merge. Exiting")
os.Exit(0)
}
var confirmedPRs []PullRequest
extensionLogger.Debugf("Selected PRs:")
var errors []error
for _, pr := range selectedPRs {
if skipPRCheckFlag {
extensionLogger.Debugf("%s\n", pr)
confirmedPRs = append(confirmedPRs, pr)
continue
}
passing, err := checkPassingChecks(pr)
if err != nil {
extensionLogger.Warnf("while fetching Github checks for #%d, skipping PR: %v\n", pr.Number, err)
errors = append(errors, err)
continue
}
if passing {
extensionLogger.Debugf("%s\n", pr)
confirmedPRs = append(confirmedPRs, pr)
} else {
extensionLogger.Warnf("Not all checks are passing for #%d, skipping PR", pr.Number)
}
}
if len(errors) == len(selectedPRs) {
extensionLogger.Errorf("All PRs failed to pass checks. Exiting")
os.Exit(1)
}
// checkout default branch
defaultBranch, err := defaultBranch()
if err != nil {
panic(err)
}
extensionLogger.Debugf("default branch is %s\n", defaultBranch)
err = updateBranch(defaultBranch)
if err != nil {
panic(err)
}
var prTitle = combineTitles(confirmedPRs)
branchName := fmt.Sprintf("%s-%s", combinedPRsBranchName, titlesHash(prTitle))
err = createBranch(branchName, defaultBranch)
if err != nil {
panic(err)
}
executable := []string{"gh", "combine-prs"}
executable = append(executable, os.Args[1:]...)
command := strings.Join(executable, " ")
disclaimer := "> [!NOTE]\n>This PR has been created with the [combine-prs](https://github.com/mdelapenya/gh-combine-prs) `gh` extension:\n\n>" + command + ".\n\n"
body := disclaimer + "It combines the following PRs:\n\n"
relatedIssuesText := "## Related Issues:\n\n"
for _, pr := range confirmedPRs {
err = checkoutPR(pr)
if err != nil {
panic(err)
}
err = mergeBranch(branchName, pr.HeadRefName)
if err != nil {
extensionLogger.Warnf("pull request #%d failed to merge into %s: %v. Skipping PR\n", pr.Number, branchName, err)
continue
}
relatedIssuesText += fmt.Sprintf("- Closes #%d\n", pr.Number)
prDescription, err := viewPR(pr)
if err != nil {
panic(err)
}
body += fmt.Sprintf("- %s\n", prDescription)
}
if len(confirmedPRs) > 0 {
body += "\n" + relatedIssuesText
}
err = checkIfCreatePR(branchName, prTitle, body)
if err != nil {
panic(err)
}
}
func defaultBranch() (string, error) {
response := struct {
DefaultBranch string `json:"default_branch"`
}{}
err := ghClient.Get("repos/"+currentRepo.Owner()+"/"+currentRepo.Name(), &response)
if err != nil {
return "", err
}
return response.DefaultBranch, nil
}
// titlesHash returns a hash of the PR titles
func titlesHash(prTitle string) string {
h := fnv.New32a()
_, err := h.Write([]byte(prTitle))
if err != nil {
panic(err)
}
return fmt.Sprintf("%d", h.Sum32())
}
func usage(exitCode int, args ...string) {
for _, arg := range args {
fmt.Fprintln(os.Stderr, arg)
}
fmt.Println(`Usage: gh multi-merge-prs --query "QUERY" [--limit 50] [--skip-pr-check] [--verbose] [--interactive] [--help]
Arguments:
`)
maxLength := 0
flag.VisitAll(func(f *flag.Flag) {
if len(f.Name) > maxLength {
maxLength = len(f.Name)
}
})
flag.VisitAll(func(f *flag.Flag) {
currentLength := len(f.Name)
fmt.Fprintf(os.Stderr, " --%s%s%s\n", f.Name, strings.Repeat(" ", maxLength-currentLength+3), f.Usage)
})
// exit execution after printing usage
os.Exit(exitCode)
}
// For more examples of using go-gh, see:
// https://github.com/cli/go-gh/blob/trunk/example_gh_test.go