-
Notifications
You must be signed in to change notification settings - Fork 23
/
push.go
572 lines (521 loc) · 15.3 KB
/
push.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package ghui
import (
"context"
"fmt"
"strings"
"emperror.dev/errors"
"github.com/aviator-co/av/internal/actions"
avconfig "github.com/aviator-co/av/internal/config"
"github.com/aviator-co/av/internal/gh"
"github.com/aviator-co/av/internal/git"
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/utils/colors"
"github.com/aviator-co/av/internal/utils/ghutils"
"github.com/aviator-co/av/internal/utils/stackutils"
"github.com/aviator-co/av/internal/utils/uiutils"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/dustin/go-humanize"
"github.com/erikgeiser/promptkit/selection"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/shurcooL/githubv4"
)
const (
continuePush = "Yes. Push the branches to GitHub."
abortPush = "No. Do not push the branches to GitHub."
reasonAlreadyUpToDate = "Already up-to-date."
reasonNotPushedToRemote = "No remote branch yet."
reasonPRIsMerged = "PR is already merged."
reasonPRIsClosed = "PR is closed."
reasonParentNotPushed = "Parent branch is not pushed to remote."
reasonNoPR = "Some branches in a stack do not have a PR."
)
type pushCandidate struct {
branch plumbing.ReferenceName
remoteCommit *object.Commit
localCommit *object.Commit
}
type noPushBranch struct {
branch plumbing.ReferenceName
reason string
}
func NewGitHubPushModel(
repo *git.Repo,
db meta.DB,
client *gh.Client,
pushFlag string,
targetBranches []plumbing.ReferenceName,
) *GitHubPushModel {
var makeDraftBeforePush bool
if avconfig.Av.PullRequest.RebaseWithDraft != nil {
makeDraftBeforePush = *avconfig.Av.PullRequest.RebaseWithDraft
} else {
makeDraftBeforePush = ghutils.HasCodeowners(repo)
}
return &GitHubPushModel{
repo: repo,
db: db,
client: client,
makeDraftBeforePush: makeDraftBeforePush,
pushFlag: pushFlag,
targetBranches: targetBranches,
spinner: spinner.New(spinner.WithSpinner(spinner.Dot)),
help: help.New(),
chooseNoPush: pushFlag == "no",
}
}
type GitHubPushProgress struct {
candidateCalculationDone bool
gitPushDone bool
}
type GitHubPushDone struct{}
type GitHubPushModel struct {
repo *git.Repo
db meta.DB
client *gh.Client
makeDraftBeforePush bool
pushFlag string
targetBranches []plumbing.ReferenceName
spinner spinner.Model
help help.Model
chooseNoPush bool
pushCandidates []pushCandidate
noPushBranches []noPushBranch
pushPrompt *selection.Model[string]
calculatingCandidates bool
askingForConfirmation bool
runningGitPush bool
done bool
}
func (vm *GitHubPushModel) Init() tea.Cmd {
vm.calculatingCandidates = true
return tea.Batch(vm.spinner.Tick, vm.calculateChangedBranches)
}
func (vm *GitHubPushModel) Update(msg tea.Msg) (*GitHubPushModel, tea.Cmd) {
switch msg := msg.(type) {
case *GitHubPushProgress:
if msg.candidateCalculationDone {
vm.calculatingCandidates = false
if len(vm.pushCandidates) == 0 || vm.chooseNoPush {
vm.done = true
return vm, func() tea.Msg { return &GitHubPushDone{} }
}
if vm.pushFlag == "yes" {
vm.runningGitPush = true
return vm, vm.runUpdate
}
vm.askingForConfirmation = true
vm.pushPrompt = uiutils.NewPromptModel("Are you OK with pushing these branches to remote?", []string{continuePush, abortPush})
return vm, vm.pushPrompt.Init()
}
if msg.gitPushDone {
vm.runningGitPush = false
vm.done = true
return vm, func() tea.Msg { return &GitHubPushDone{} }
}
case tea.KeyMsg:
if vm.askingForConfirmation {
switch msg.String() {
case "enter":
c, err := vm.pushPrompt.Value()
if err != nil {
return vm, func() tea.Msg { return err }
}
vm.askingForConfirmation = false
vm.pushPrompt = nil
if c != continuePush {
vm.chooseNoPush = true
vm.done = true
return vm, func() tea.Msg { return &GitHubPushDone{} }
}
vm.runningGitPush = true
return vm, vm.runUpdate
case "ctrl+c":
return vm, tea.Quit
default:
_, cmd := vm.pushPrompt.Update(msg)
return vm, cmd
}
}
case spinner.TickMsg:
var cmd tea.Cmd
vm.spinner, cmd = vm.spinner.Update(msg)
return vm, cmd
}
return vm, nil
}
func (vm *GitHubPushModel) View() string {
if vm.calculatingCandidates {
return colors.ProgressStyle.Render(vm.spinner.View() + "Finding the changed branches...")
}
sb := strings.Builder{}
if len(vm.pushCandidates) == 0 {
sb.WriteString(colors.SuccessStyle.Render("✓ Nothing to push to GitHub"))
} else if vm.askingForConfirmation {
sb.WriteString("Confirming the push to GitHub")
} else if vm.runningGitPush {
sb.WriteString(colors.ProgressStyle.Render(vm.spinner.View() + "Pushing to GitHub..."))
} else if vm.done {
if vm.chooseNoPush {
sb.WriteString(colors.SuccessStyle.Render("✓ Not pushing to GitHub"))
} else {
sb.WriteString(colors.SuccessStyle.Render("✓ Pushed to GitHub"))
}
}
if len(vm.noPushBranches) > 0 || len(vm.pushCandidates) > 0 {
sb.WriteString("\n")
}
if len(vm.noPushBranches) > 0 {
sb.WriteString("\n")
sb.WriteString(" Following branches do not need a push.\n")
sb.WriteString("\n")
sb.WriteString(lipgloss.NewStyle().MarginLeft(4).Render(vm.viewNoPushBranches()))
}
if len(vm.pushCandidates) > 0 {
sb.WriteString("\n")
if vm.runningGitPush {
sb.WriteString(" Following branches are being pushed...\n")
} else if vm.done && !vm.chooseNoPush {
sb.WriteString(" Following branches are pushed.\n")
} else {
sb.WriteString(" Following branches need to be pushed.\n")
}
sb.WriteString("\n")
sb.WriteString(lipgloss.NewStyle().MarginLeft(4).Render(vm.viewPushCandidates()))
}
if vm.pushPrompt != nil {
sb.WriteString("\n")
sb.WriteString(vm.pushPrompt.View())
sb.WriteString(vm.help.ShortHelpView(uiutils.PromptKeys))
}
return sb.String()
}
func (vm *GitHubPushModel) viewPushCandidates() string {
sb := strings.Builder{}
for i, branch := range vm.pushCandidates {
if i > 0 {
sb.WriteString("\n")
}
sb.WriteString(branch.branch.Short() + "\n")
sb.WriteString(
" Remote: " + branch.remoteCommit.Hash.String()[:7] + " " + getFirstLine(
branch.remoteCommit.Message,
) + " " + branch.remoteCommit.Committer.When.String() + " (" + humanize.Time(
branch.remoteCommit.Committer.When,
) + ")\n",
)
sb.WriteString(
" Local: " + branch.localCommit.Hash.String()[:7] + " " + getFirstLine(
branch.localCommit.Message,
) + " " + branch.localCommit.Committer.When.String() + " (" + humanize.Time(
branch.localCommit.Committer.When,
) + ")\n",
)
avbr, _ := vm.db.ReadTx().Branch(branch.branch.Short())
if avbr.PullRequest != nil && avbr.PullRequest.Permalink != "" {
sb.WriteString(" PR: " + avbr.PullRequest.Permalink + "\n")
}
}
return sb.String()
}
func (vm *GitHubPushModel) viewNoPushBranches() string {
sb := strings.Builder{}
for _, branch := range vm.noPushBranches {
sb.WriteString(branch.branch.Short() + ": " + branch.reason + "\n")
}
return sb.String()
}
func (vm *GitHubPushModel) runUpdate() (ret tea.Msg) {
ghPRs, err := vm.getPRs()
if err != nil {
return err
}
if vm.makeDraftBeforePush {
if err := vm.makePRsDraft(ghPRs); err != nil {
return err
}
}
defer func() {
if vm.makeDraftBeforePush {
if err := vm.undraftPRs(ghPRs); err != nil {
ret = err
}
}
}()
if err := vm.updatePRs(ghPRs); err != nil {
return err
}
if err := vm.runGitPush(); err != nil {
return err
}
return &GitHubPushProgress{gitPushDone: true}
}
func (vm *GitHubPushModel) runGitPush() error {
pushArgs := []string{"push", vm.repo.GetRemoteName(), "--atomic"}
for _, branch := range vm.pushCandidates {
// Do a compare-and-swap to be strict on what we show as a difference.
pushArgs = append(
pushArgs,
fmt.Sprintf(
"--force-with-lease=%s:%s",
branch.branch.String(),
branch.remoteCommit.Hash.String(),
),
)
}
for _, branch := range vm.pushCandidates {
// Push the exact commit hash to be strict on what we show as a difference.
pushArgs = append(pushArgs,
fmt.Sprintf("%s:%s", branch.localCommit.Hash.String(), branch.branch.String()),
)
}
res, err := vm.repo.Run(&git.RunOpts{
Args: pushArgs,
})
if err != nil {
return errors.WrapIff(err, "failed to push branches to GitHub")
}
if res.ExitCode != 0 {
return errors.Errorf("failed to push branches to GitHub\n%s\n%s", res.Stdout, res.Stderr)
}
for _, branch := range vm.pushCandidates {
if err := vm.repo.BranchSetConfig(branch.branch.Short(), "av-pushed-remote", vm.repo.GetRemoteName()); err != nil {
return err
}
if err := vm.repo.BranchSetConfig(branch.branch.Short(), "av-pushed-ref", branch.branch.String()); err != nil {
return err
}
if err := vm.repo.BranchSetConfig(branch.branch.Short(), "av-pushed-commit", branch.localCommit.Hash.String()); err != nil {
return err
}
}
return nil
}
func (vm *GitHubPushModel) getPRs() (map[plumbing.ReferenceName]*gh.PullRequest, error) {
prs := map[plumbing.ReferenceName]*gh.PullRequest{}
for _, branch := range vm.pushCandidates {
avbr, _ := vm.db.ReadTx().Branch(branch.branch.Short())
if avbr.PullRequest != nil {
pr, err := vm.client.PullRequest(context.Background(), avbr.PullRequest.ID)
if err != nil {
return nil, err
}
prs[branch.branch] = pr
}
}
return prs, nil
}
func (vm *GitHubPushModel) makePRsDraft(ghPRs map[plumbing.ReferenceName]*gh.PullRequest) error {
for _, pr := range ghPRs {
if pr.State == "OPEN" && !pr.IsDraft {
if _, err := vm.client.ConvertPullRequestToDraft(context.Background(), pr.ID); err != nil {
return err
}
}
}
return nil
}
func (vm *GitHubPushModel) updatePRs(ghPRs map[plumbing.ReferenceName]*gh.PullRequest) error {
for br, pr := range ghPRs {
avbr, _ := vm.db.ReadTx().Branch(br.Short())
prMeta := createPRMetadata(avbr, vm)
var stackToWrite *stackutils.StackTreeNode
if avconfig.Av.PullRequest.WriteStack {
var err error
if stackToWrite, err = stackutils.BuildStackTreeCurrentStack(vm.db.ReadTx(), br.Short(), false); err != nil {
return err
}
}
prBody := actions.AddPRMetadataAndStack(
pr.Body,
prMeta,
avbr.Name,
stackToWrite,
vm.db.ReadTx(),
)
if _, err := vm.client.UpdatePullRequest(context.Background(), githubv4.UpdatePullRequestInput{
PullRequestID: pr.ID,
BaseRefName: githubv4.NewString(githubv4.String(avbr.Parent.Name)),
Body: githubv4.NewString(githubv4.String(prBody)),
}); err != nil {
return err
}
}
return nil
}
func (vm *GitHubPushModel) undraftPRs(ghPRs map[plumbing.ReferenceName]*gh.PullRequest) error {
for _, pr := range ghPRs {
if pr.State == "OPEN" && !pr.IsDraft {
if _, err := vm.client.MarkPullRequestReadyForReview(context.Background(), pr.ID); err != nil {
return err
}
}
}
return nil
}
func (vm *GitHubPushModel) calculateChangedBranches() tea.Msg {
repo := vm.repo.GoGitRepo()
remote, err := repo.Remote(vm.repo.GetRemoteName())
if err != nil {
return errors.Errorf("failed to get remote %s: %v", vm.repo.GetRemoteName(), err)
}
remoteConfig := remote.Config()
var noPushBranches []noPushBranch
var pushCandidates []pushCandidate
for _, br := range vm.targetBranches {
avbr, _ := vm.db.ReadTx().Branch(br.Short())
if avbr.MergeCommit != "" ||
(avbr.PullRequest != nil && avbr.PullRequest.State == "MERGED") {
noPushBranches = append(noPushBranches, noPushBranch{
branch: br,
reason: reasonPRIsMerged,
})
continue
}
if avbr.PullRequest != nil && avbr.PullRequest.State == "CLOSED" {
noPushBranches = append(noPushBranches, noPushBranch{
branch: br,
reason: reasonPRIsClosed,
})
continue
}
rtb := mapToRemoteTrackingBranch(remoteConfig, br)
if rtb == nil {
noPushBranches = append(noPushBranches, noPushBranch{
branch: br,
reason: reasonNotPushedToRemote,
})
continue
}
remoteRef, err := repo.Reference(*rtb, true)
if err != nil {
noPushBranches = append(noPushBranches, noPushBranch{
branch: br,
reason: reasonNotPushedToRemote,
})
continue
}
localRef, err := repo.Reference(br, true)
if err != nil {
return err
}
if localRef.Hash() == remoteRef.Hash() && !isDifferencePRMetadata(avbr, vm) {
noPushBranches = append(noPushBranches, noPushBranch{
branch: br,
reason: reasonAlreadyUpToDate,
})
continue
}
if !vm.allParentsHaveRemoteTrackingBranch(remoteConfig, br) {
// If a parent doesn't have a remote tracking branch, the PR cannot be made
// with that branch as the base. We cannot push this branch.
noPushBranches = append(noPushBranches, noPushBranch{
branch: br,
reason: reasonParentNotPushed,
})
continue
}
if !vm.allBranchesOnStackHavePRs(br) {
// If an ancestor branch doesn't have a PR, the PR cannot be made with the
// right metadata.
noPushBranches = append(noPushBranches, noPushBranch{
branch: br,
reason: reasonNoPR,
})
continue
}
remoteRefCommit, err := repo.CommitObject(remoteRef.Hash())
if err != nil {
return err
}
localRefCommit, err := repo.CommitObject(localRef.Hash())
if err != nil {
return err
}
pushCandidates = append(pushCandidates, pushCandidate{
branch: br,
remoteCommit: remoteRefCommit,
localCommit: localRefCommit,
})
}
vm.noPushBranches = noPushBranches
vm.pushCandidates = pushCandidates
return &GitHubPushProgress{candidateCalculationDone: true}
}
func (vm *GitHubPushModel) allParentsHaveRemoteTrackingBranch(
remoteConfig *config.RemoteConfig,
br plumbing.ReferenceName,
) bool {
avbr, _ := vm.db.ReadTx().Branch(br.Short())
parent := avbr.Parent
for !parent.Trunk {
avbr, _ := vm.db.ReadTx().Branch(parent.Name)
rtb := mapToRemoteTrackingBranch(remoteConfig, plumbing.NewBranchReferenceName(parent.Name))
if rtb == nil {
return false
}
parent = avbr.Parent
}
return true
}
func (vm *GitHubPushModel) allBranchesOnStackHavePRs(br plumbing.ReferenceName) bool {
avbr, _ := vm.db.ReadTx().Branch(br.Short())
for {
if avbr.PullRequest == nil {
return false
}
if avbr.Parent.Trunk {
return true
}
avbr, _ = vm.db.ReadTx().Branch(avbr.Parent.Name)
}
}
func getFirstLine(s string) string {
idx := strings.Index(s, "\n")
if idx == -1 {
return s
}
return s[:idx]
}
func createPRMetadata(branch meta.Branch, vm *GitHubPushModel) actions.PRMetadata {
trunk, _ := meta.Trunk(vm.db.ReadTx(), branch.Name)
metadata := actions.PRMetadata{
Parent: branch.Parent.Name,
ParentHead: branch.Parent.Head,
Trunk: trunk,
}
if !branch.Parent.Trunk {
parent, _ := vm.db.ReadTx().Branch(branch.Parent.Name)
if parent.PullRequest != nil {
metadata.ParentPull = parent.PullRequest.Number
}
}
return metadata
}
// Compare local metadata with PR metadata for any changes
func isDifferencePRMetadata(avbr meta.Branch, vm *GitHubPushModel) bool {
local := createPRMetadata(avbr, vm)
prs, err := vm.getPRs()
if err != nil {
return true
}
var pr *gh.PullRequest
for _, p := range prs {
if avbr.PullRequest.ID == p.ID {
pr = p
break
}
}
if pr == nil {
return true
}
prMeta, err := actions.ReadPRMetadata(pr.Body)
if err != nil {
return true
}
return local == prMeta
}