-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathgithub.go
More file actions
255 lines (235 loc) · 8.06 KB
/
Copy pathgithub.go
File metadata and controls
255 lines (235 loc) · 8.06 KB
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
package main
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
type NewPRBody struct {
Title string `json:"title"`
Body string `json:"body"`
Head string `json:"head"`
Base string `json:"base"`
}
type PR struct {
Number int `json:"number"`
Body string `json:"body"`
Head struct {
Ref string `json:"ref"`
} `json:"head"`
Base struct {
Ref string `json:"ref"`
} `json:"base"`
// Stack is non-nil when the PR is part of a GitHub native stack. It is the
// signal that base edits via `gh pr edit --base` are blocked, and it carries
// the stack Number needed to dissolve the stack (`gh stack unstack <n>`).
Stack *struct {
Number int `json:"number"`
Size int `json:"size"`
Position int `json:"position"`
} `json:"stack"`
UpdatedAt *time.Time
}
func githubGetPRNumberForCommit(commit *Commit, base string) (int, error) {
if commit.PRNumber != 0 {
return commit.PRNumber, nil
}
ghURL := ghAPIURL("commits/%v/pulls?per_page=100", commit.Hash)
jsonBody, err := httpGET(ghURL)
switch {
case err != nil && strings.Contains(err.Error(), "No commit found"):
return githubSearchPRNumberForCommit(commit)
case err != nil:
return 0, err
}
var out []PR
err = json.Unmarshal(jsonBody, &out)
if err != nil {
return 0, errorf("failed to parse request body: %v", err)
}
remoteRef := commit.GetRemoteRef()
if remoteRef != "" {
for _, pr := range out {
if pr.Head.Ref == remoteRef {
return pr.Number, nil
}
}
}
if commit.Skip {
return githubSearchPRNumberForCommit(commit)
}
// the commit was pushed and got "Everything up-to-date", try creating new pr
err = githubCreatePRForCommit(commit, base)
if err != nil {
return 0, err
}
return commit.PRNumber, nil
}
// githubLookupPRNumber returns the existing PR number for a commit by querying
// the GitHub API and matching against the commit's Remote-Ref branch. Returns
// 0 if no PR is found or the lookup fails. Unlike githubGetPRNumberForCommit,
// this never creates a PR — used to populate PRNumber for commits in fullStack
// that are outside the selected push range, so stack-info bullets render the
// real PR links even for non-selected commits.
func githubLookupPRNumber(commit *Commit) int {
if commit.PRNumber != 0 {
return commit.PRNumber
}
remoteRef := commit.GetRemoteRef()
if remoteRef == "" {
return 0
}
ghURL := ghAPIURL("commits/%v/pulls?per_page=100", commit.Hash)
jsonBody, err := httpGET(ghURL)
if err != nil {
return 0
}
var out []PR
if err := json.Unmarshal(jsonBody, &out); err != nil {
return 0
}
for _, pr := range out {
if pr.Head.Ref == remoteRef {
return pr.Number
}
}
return 0
}
func githubGetPRByNumber(number int) (*PR, error) {
ghURL := ghAPIURL("pulls/%d", number)
jsonBody, err := httpGET(ghURL)
if err != nil {
return nil, err
}
var out PR
err = json.Unmarshal(jsonBody, &out)
if err != nil {
return nil, errorf("failed to parse request body: %v", err)
}
return &out, nil
}
var regexpPRURL = regexp.MustCompile(`/pull/(\d+)`)
func githubCreatePRForCommit(commit *Commit, base string) error {
args := []string{"pr", "create", "--title", commit.Title, "--body", "", "--head", commit.GetRemoteRef(), "--base", base}
if tags := commit.GetTags(config.tags...); len(tags) > 0 {
args = append(args, "--label", strings.Join(tags, ","))
}
printf("create pull request for %q\n", commit.Title)
out, err := gh(args...)
if err != nil {
return err
}
m := regexpPRURL.FindStringSubmatch(out)
if m == nil {
return errorf("failed to parse PR number from gh pr create output: %v", out)
}
n, err := strconv.Atoi(m[1])
if err != nil {
return errorf("failed to parse PR number %q: %v", m[1], err)
}
commit.PRNumber = n
return nil
}
func githubPRUpdateBaseForCommit(commit *Commit, base string) error {
prNumber, err := githubGetPRNumberForCommit(commit, base)
if err != nil {
return err
}
// Record the resolved number now (githubGetPRNumberForCommit doesn't set it
// on branch-matched PRs until a later phase) so a deferred stack realign and
// its warning can name the PR.
if commit.PRNumber == 0 {
commit.PRNumber = prNumber
}
// Skip the edit when the base already matches: this avoids a needless
// updatePullRequest mutation, which GitHub blocks on natively-stacked PRs.
// If the pre-check fetch fails, fall through and attempt the edit anyway.
if pr, perr := githubGetPRByNumber(prNumber); perr == nil && pr != nil && pr.Base.Ref == base {
debugf("PR #%d base already %q, skip base edit", prNumber, base)
return nil
}
_, err = gh("pr", "edit", strconv.Itoa(prNumber), "--base", base)
if isBaseChangeBlockedByStack(err) {
// GitHub owns the base branch of a natively-stacked PR and rejects
// updatePullRequest. Record it so main() can realign the whole stack
// once, after the push barrier (with confirmation), instead of
// crashing here inside a push goroutine.
commit.BaseBlocked = true
debugf("PR #%d base change to %q blocked by native stack; deferring realign", prNumber, base)
return nil
}
return err
}
// isBaseChangeBlockedByStack reports whether err is GitHub rejecting a
// base-branch edit because the PR is part of a native stack, e.g.
// "GraphQL: Cannot change the base branch because the pull request is part of
// a stack. (updatePullRequest)".
func isBaseChangeBlockedByStack(err error) bool {
return err != nil && strings.Contains(err.Error(), "part of a stack")
}
// isGhStackMissing reports whether a `gh stack ...` call failed because the
// gh-stack extension is not installed (`unknown command "stack" for "gh"`).
func isGhStackMissing(out string, err error) bool {
return err != nil && strings.Contains(out+err.Error(), "unknown command")
}
// isStackWouldRemove reports whether `gh stack link` refused because updating the
// stack to the given branches would drop a PR from it, e.g.
// "✗ Cannot update stack: this would remove #22054 from the stack".
func isStackWouldRemove(out string, err error) bool {
return err != nil && strings.Contains(out+err.Error(), "would remove")
}
// githubStackNumberForCommits returns the native stack number that the commits'
// PRs belong to (0 if none are in a stack). The number lives on each PR's stack
// field; the first non-nil one wins.
func githubStackNumberForCommits(commits []*Commit) int {
for _, commit := range commits {
if commit.PRNumber == 0 {
continue
}
if pr, err := githubGetPRByNumber(commit.PRNumber); err == nil && pr != nil && pr.Stack != nil {
return pr.Stack.Number
}
}
return 0
}
// githubStackRealign rebuilds the native GitHub stack numbered stackNumber so it
// matches the local stack `branches` (ordered bottom→top). gh-stack's `link`
// never removes a PR from an existing stack and `modify` is interactive-only, so
// the only scriptable way to drop the orphaned PR(s) is to dissolve the whole
// stack (`gh stack unstack <n>`) and relink just the local branches into a fresh
// stack, which recreates it with correct base chaining. Any PR no longer in the
// chain is left as a standalone open PR.
func githubStackRealign(stackNumber int, branches []string) error {
out, err := gh("stack", "unstack", strconv.Itoa(stackNumber))
if err != nil {
if strings.Contains(out+err.Error(), "unknown command") {
return errorf("git-pr needs the gh-stack extension to fix a native GitHub stack:\n" +
" gh extension install github/gh-stack")
}
return errorf("gh stack unstack %d failed: %v", stackNumber, err)
}
if _, err := gh(append([]string{"stack", "link"}, branches...)...); err != nil {
return errorf("gh stack link %s failed: %v", strings.Join(branches, " "), err)
}
return nil
}
var regexpNumber = regexp.MustCompile(`[0-9]+`)
func githubSearchPRNumberForCommit(commit *Commit) (int, error) {
query := fmt.Sprintf("in:title %v", commit.Title)
result, err := gh("pr", "list", "--limit=1", "--search", query)
if err != nil {
debugf("failed to search PR for commit (ignored) %q: %v\n", commit.Title, err)
return 0, nil
}
s := regexpNumber.FindString(result)
if s == "" {
return 0, nil
}
n, err := strconv.Atoi(s)
if err != nil {
return 0, errorf("failed to parse PR number %q: %v", s, err)
}
return n, nil
}