-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathsubmit_test.go
More file actions
2591 lines (2232 loc) · 78.6 KB
/
Copy pathsubmit_test.go
File metadata and controls
2591 lines (2232 loc) · 78.6 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
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/cli/go-gh/v2/pkg/api"
"github.com/github/gh-stack/internal/config"
"github.com/github/gh-stack/internal/git"
"github.com/github/gh-stack/internal/github"
"github.com/github/gh-stack/internal/modify"
"github.com/github/gh-stack/internal/stack"
"github.com/github/gh-stack/internal/tui/submitview"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGeneratePRBody(t *testing.T) {
tests := []struct {
name string
commitBody string
templateContent string
wantContains []string
wantNotContains []string
}{
{
name: "empty commit body no template",
commitBody: "",
wantContains: []string{
"GitHub Stacks CLI",
feedbackURL,
"<sub>",
},
},
{
name: "with commit body no template",
commitBody: "This is a detailed description\nof the change.",
wantContains: []string{
"This is a detailed description\nof the change.",
"GitHub Stacks CLI",
"<sub>",
},
},
{
name: "with template",
commitBody: "some commit body",
templateContent: "## Description\n\nFill in details.",
wantContains: []string{
"## Description",
"Fill in details.",
},
wantNotContains: []string{
"GitHub Stacks CLI",
feedbackURL,
"some commit body",
},
},
{
name: "template replaces footer",
templateContent: "Template body only",
wantContains: []string{"Template body only"},
wantNotContains: []string{"<sub>"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := generatePRBody(tt.commitBody, tt.templateContent)
for _, want := range tt.wantContains {
assert.Contains(t, got, want)
}
for _, notWant := range tt.wantNotContains {
assert.NotContains(t, got, notWant)
}
})
}
}
// newSubmitMock creates a MockOps pre-configured for submit tests.
func newSubmitMock(tmpDir string, currentBranch string) *git.MockOps {
return &git.MockOps{
GitDirFn: func() (string, error) { return tmpDir, nil },
RootDirFn: func() (string, error) { return tmpDir, nil },
CurrentBranchFn: func() (string, error) { return currentBranch, nil },
ResolveRemoteFn: func(string) (string, error) { return "origin", nil },
PushFn: func(string, []string, bool, bool) error { return nil },
}
}
func TestSubmit_CreatesPRsAndStack(t *testing.T) {
s := stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1"},
{Branch: "b2"},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
var pushCalls []pushCall
var createdPRs []string
mock := newSubmitMock(tmpDir, "b1")
mock.PushFn = func(remote string, branches []string, force, atomic bool) error {
pushCalls = append(pushCalls, pushCall{remote, branches, force, atomic})
return nil
}
mock.LogRangeFn = func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{{Subject: "commit for " + head}}, nil
}
restore := git.SetOps(mock)
defer restore()
prCounter := 100
cfg, _, errR := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{
FindPRForBranchFn: func(branch string) (*github.PullRequest, error) {
return nil, nil // No existing PR
},
CreatePRFn: func(base, head, title, body string, draft bool) (*github.PullRequest, error) {
createdPRs = append(createdPRs, head)
prCounter++
return &github.PullRequest{
Number: prCounter,
ID: fmt.Sprintf("PR_%d", prCounter),
URL: fmt.Sprintf("https://github.com/owner/repo/pull/%d", prCounter),
}, nil
},
CreateStackFn: func(prNumbers []int) (*github.RemoteStack, error) {
return &github.RemoteStack{ID: 42, Number: 42}, nil
},
}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.NoError(t, err)
// Branches should be pushed (sequentially, one per branch)
require.Len(t, pushCalls, 2)
assert.Equal(t, "origin", pushCalls[0].remote)
assert.Equal(t, []string{"b1"}, pushCalls[0].branches)
assert.Equal(t, []string{"b2"}, pushCalls[1].branches)
// PRs should be created
assert.Equal(t, []string{"b1", "b2"}, createdPRs)
// Stack should be created
assert.Contains(t, output, "Stack created on GitHub with 2 PRs")
assert.Contains(t, output, "Pushed and synced 2 branches")
}
func TestSubmit_DefaultDraft(t *testing.T) {
s := stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1"},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
var createdDraft bool
mock := newSubmitMock(tmpDir, "b1")
mock.PushFn = func(string, []string, bool, bool) error { return nil }
mock.LogRangeFn = func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{{Subject: "commit for " + head}}, nil
}
restore := git.SetOps(mock)
defer restore()
cfg, _, _ := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{
ListStacksFn: func() ([]github.RemoteStack, error) { return nil, nil },
FindPRForBranchFn: func(string) (*github.PullRequest, error) { return nil, nil },
CreatePRFn: func(base, head, title, body string, draft bool) (*github.PullRequest, error) {
createdDraft = draft
return &github.PullRequest{Number: 1, ID: "PR_1", URL: "https://github.com/o/r/pull/1"}, nil
},
CreateStackFn: func([]int) (*github.RemoteStack, error) { return &github.RemoteStack{ID: 1, Number: 1}, nil },
}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
assert.NoError(t, err)
assert.True(t, createdDraft, "PRs should be created as drafts by default")
}
func TestSubmit_OpenFlag(t *testing.T) {
s := stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1"},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
var createdDraft bool
mock := newSubmitMock(tmpDir, "b1")
mock.PushFn = func(string, []string, bool, bool) error { return nil }
mock.LogRangeFn = func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{{Subject: "commit for " + head}}, nil
}
restore := git.SetOps(mock)
defer restore()
cfg, _, _ := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{
ListStacksFn: func() ([]github.RemoteStack, error) { return nil, nil },
FindPRForBranchFn: func(string) (*github.PullRequest, error) { return nil, nil },
CreatePRFn: func(base, head, title, body string, draft bool) (*github.PullRequest, error) {
createdDraft = draft
return &github.PullRequest{Number: 1, ID: "PR_1", URL: "https://github.com/o/r/pull/1"}, nil
},
CreateStackFn: func([]int) (*github.RemoteStack, error) { return &github.RemoteStack{ID: 1, Number: 1}, nil },
}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto", "--open"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
assert.NoError(t, err)
assert.False(t, createdDraft, "PRs should not be created as drafts when --open is set")
}
func TestSubmit_OpenFlag_ConvertsDraftPRs(t *testing.T) {
s := stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10, ID: "PR_10"}},
{Branch: "b2"},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
var markedReady []string
mock := newSubmitMock(tmpDir, "b1")
mock.PushFn = func(string, []string, bool, bool) error { return nil }
mock.LogRangeFn = func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{{Subject: "commit for " + head}}, nil
}
restore := git.SetOps(mock)
defer restore()
cfg, _, errR := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{
ListStacksFn: func() ([]github.RemoteStack, error) { return nil, nil },
FindPRForBranchFn: func(branch string) (*github.PullRequest, error) {
switch branch {
case "b1":
return &github.PullRequest{
Number: 10, ID: "PR_10", HeadRefName: "b1", BaseRefName: "main",
IsDraft: true, URL: "https://github.com/o/r/pull/10",
}, nil
}
return nil, nil
},
CreatePRFn: func(base, head, title, body string, draft bool) (*github.PullRequest, error) {
return &github.PullRequest{
Number: 11, ID: "PR_11", URL: "https://github.com/o/r/pull/11",
}, nil
},
MarkPRReadyForReviewFn: func(prID string) error {
markedReady = append(markedReady, prID)
return nil
},
CreateStackFn: func([]int) (*github.RemoteStack, error) { return &github.RemoteStack{ID: 1, Number: 1}, nil },
}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto", "--open"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.NoError(t, err)
assert.Equal(t, []string{"PR_10"}, markedReady, "existing draft PR should be marked ready")
assert.Contains(t, output, "Marked PR")
}
func TestSubmit_PushFailure(t *testing.T) {
s := stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1"},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
mock := newSubmitMock(tmpDir, "b1")
mock.PushFn = func(string, []string, bool, bool) error {
return fmt.Errorf("remote rejected")
}
restore := git.SetOps(mock)
defer restore()
cfg, _, errR := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.ErrorIs(t, err, ErrSilent)
assert.Contains(t, output, "failed to push")
}
func TestSubmit_SkipsMergedBranches(t *testing.T) {
s := stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 1, Merged: true}},
{Branch: "b2"},
{Branch: "b3", PullRequest: &stack.PullRequestRef{Number: 3, Merged: true}},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
var pushCalls []pushCall
mock := newSubmitMock(tmpDir, "b2")
mock.PushFn = func(remote string, branches []string, force, atomic bool) error {
pushCalls = append(pushCalls, pushCall{remote, branches, force, atomic})
return nil
}
restore := git.SetOps(mock)
defer restore()
cfg, _, errR := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{
FindPRForBranchFn: func(branch string) (*github.PullRequest, error) {
// Only return an OPEN PR for the active branch (b2).
// Merged branches (b1, b3) should have no open PR.
if branch == "b2" {
return &github.PullRequest{Number: 2, URL: "https://github.com/owner/repo/pull/2", State: "OPEN"}, nil
}
return nil, nil
},
}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
cfg.Err.Close()
_, _ = io.ReadAll(errR)
assert.NoError(t, err)
require.Len(t, pushCalls, 1)
assert.Equal(t, []string{"b2"}, pushCalls[0].branches)
}
// TestSubmit_ForksWhenRemoteStackFullyMerged covers the case where every PR
// officially part of the stack on GitHub has merged and the user has added new
// branches on top. Submit should lift the new branches into a fresh stack rooted
// at the trunk and create a new stack on GitHub, leaving the merged stack alone.
func TestSubmit_ForksWhenRemoteStackFullyMerged(t *testing.T) {
tests := []struct {
name string
branchesExist bool // do the merged branches still exist locally?
wantStackCount int
}{
{name: "removes old stack when merged branches are gone", branchesExist: false, wantStackCount: 1},
{name: "keeps old stack when merged branches still exist", branchesExist: true, wantStackCount: 2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := stack.Stack{
ID: "42",
Number: 42,
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 1, Merged: true}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 2, Merged: true}},
{Branch: "b3"},
{Branch: "b4"},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
var pushCalls []pushCall
var createdPRs []string
var createStackPRs []int
mock := newSubmitMock(tmpDir, "b4")
mock.PushFn = func(remote string, branches []string, force, atomic bool) error {
pushCalls = append(pushCalls, pushCall{remote, branches, force, atomic})
return nil
}
mock.LogRangeFn = func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{{Subject: "commit for " + head}}, nil
}
mock.MergeBaseFn = func(a, b string) (string, error) { return "basesha", nil }
mock.RevParseFn = func(ref string) (string, error) { return "sha-" + ref, nil }
mock.BranchExistsFn = func(string) bool { return tt.branchesExist }
restore := git.SetOps(mock)
defer restore()
prCounter := 100
cfg, _, errR := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{
ListStacksFn: func() ([]github.RemoteStack, error) {
return []github.RemoteStack{{ID: 42, PullRequests: []int{1, 2}}}, nil
},
FindPRByNumberFn: func(n int) (*github.PullRequest, error) {
switch n {
case 1:
return &github.PullRequest{Number: 1, HeadRefName: "b1", State: "MERGED", Merged: true}, nil
case 2:
return &github.PullRequest{Number: 2, HeadRefName: "b2", State: "MERGED", Merged: true}, nil
}
return &github.PullRequest{Number: n, State: "OPEN"}, nil
},
FindPRForBranchFn: func(string) (*github.PullRequest, error) { return nil, nil },
CreatePRFn: func(base, head, title, body string, draft bool) (*github.PullRequest, error) {
createdPRs = append(createdPRs, head)
prCounter++
return &github.PullRequest{
Number: prCounter,
ID: fmt.Sprintf("PR_%d", prCounter),
URL: fmt.Sprintf("https://github.com/o/r/pull/%d", prCounter),
HeadRefName: head,
}, nil
},
CreateStackFn: func(prNumbers []int) (*github.RemoteStack, error) {
createStackPRs = prNumbers
return &github.RemoteStack{ID: 99, Number: 99}, nil
},
}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
require.NoError(t, err)
// Only the new branches are pushed; merged ones are left behind.
require.Len(t, pushCalls, 2)
assert.Equal(t, []string{"b3"}, pushCalls[0].branches)
assert.Equal(t, []string{"b4"}, pushCalls[1].branches)
// Fork messaging.
assert.Contains(t, output, "Every PR in this stack has already been merged")
assert.Contains(t, output, "starting a new stack")
// PRs are created for the new branches and grouped into a new stack.
assert.Equal(t, []string{"b3", "b4"}, createdPRs)
assert.Equal(t, []int{101, 102}, createStackPRs)
// The local stack file is split: the new branches form their own
// stack rooted at the trunk with the freshly created remote ID.
reloaded, err := stack.Load(tmpDir)
require.NoError(t, err)
require.Len(t, reloaded.Stacks, tt.wantStackCount)
forked := reloaded.FindAllStacksForBranch("b4")
require.Len(t, forked, 1)
assert.Equal(t, []string{"b3", "b4"}, forked[0].BranchNames())
assert.Equal(t, "99", forked[0].ID)
assert.Equal(t, "main", forked[0].Trunk.Branch)
oldStack := reloaded.FindAllStacksForBranch("b1")
if tt.branchesExist {
require.Len(t, oldStack, 1)
assert.Equal(t, []string{"b1", "b2"}, oldStack[0].BranchNames())
assert.Equal(t, "42", oldStack[0].ID)
} else {
assert.Empty(t, oldStack)
}
})
}
}
// TestSubmit_NoForkWhenRemoteStackHasOpenPR verifies that a normal partially
// merged stack (the remote stack still has an open PR) is NOT forked — that is
// the everyday bottom-up merge flow and must keep working as before.
func TestSubmit_NoForkWhenRemoteStackHasOpenPR(t *testing.T) {
s := stack.Stack{
ID: "42",
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 1, Merged: true}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 2, Merged: true}},
{Branch: "b3", PullRequest: &stack.PullRequestRef{Number: 3}},
{Branch: "b4"},
},
}
tmpDir := t.TempDir()
writeStackFile(t, tmpDir, s)
var pushCalls []pushCall
mock := newSubmitMock(tmpDir, "b4")
mock.PushFn = func(remote string, branches []string, force, atomic bool) error {
pushCalls = append(pushCalls, pushCall{remote, branches, force, atomic})
return nil
}
mock.LogRangeFn = func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{{Subject: "commit for " + head}}, nil
}
mock.MergeBaseFn = func(a, b string) (string, error) { return "basesha", nil }
mock.RevParseFn = func(ref string) (string, error) { return "sha-" + ref, nil }
mock.BranchExistsFn = func(string) bool { return true }
restore := git.SetOps(mock)
defer restore()
prCounter := 100
cfg, _, errR := config.NewTestConfig()
cfg.GitHubClientOverride = &github.MockClient{
ListStacksFn: func() ([]github.RemoteStack, error) {
return []github.RemoteStack{{ID: 42, Number: 42, PullRequests: []int{1, 2, 3}}}, nil
},
FindPRByNumberFn: func(n int) (*github.PullRequest, error) {
switch n {
case 1:
return &github.PullRequest{Number: 1, HeadRefName: "b1", State: "MERGED", Merged: true}, nil
case 2:
return &github.PullRequest{Number: 2, HeadRefName: "b2", State: "MERGED", Merged: true}, nil
case 3:
return &github.PullRequest{Number: 3, HeadRefName: "b3", State: "OPEN"}, nil
}
return &github.PullRequest{Number: n, State: "OPEN"}, nil
},
FindPRForBranchFn: func(string) (*github.PullRequest, error) { return nil, nil },
CreatePRFn: func(base, head, title, body string, draft bool) (*github.PullRequest, error) {
prCounter++
return &github.PullRequest{
Number: prCounter,
ID: fmt.Sprintf("PR_%d", prCounter),
URL: fmt.Sprintf("https://github.com/o/r/pull/%d", prCounter),
HeadRefName: head,
}, nil
},
GetStackFn: func(int) (*github.RemoteStack, error) {
return &github.RemoteStack{ID: 42, Number: 42, PullRequests: []int{1, 2, 3}}, nil
},
AddToStackFn: func(int, []int) (*github.RemoteStack, error) {
// Merged-and-deleted base branches break the chain on GitHub.
return nil, &api.HTTPError{
StatusCode: 422,
Message: "Pull requests must form a stack, where each PR's base ref is the previous PR's head ref",
RequestURL: &url.URL{Path: "/repos/o/r/stacks/42/add"},
}
},
}
cmd := SubmitCmd(cfg)
cmd.SetArgs([]string{"--auto"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
require.NoError(t, err)
// No fork happened.
assert.NotContains(t, output, "starting a new stack")
// The broken-chain update is explained calmly, not as a scary failure.
assert.Contains(t, output, "Merged PRs have left the stack")
assert.NotContains(t, output, "Failed to update stack")
// The local stack file is untouched: still a single stack with all branches.
reloaded, err := stack.Load(tmpDir)
require.NoError(t, err)
require.Len(t, reloaded.Stacks, 1)
assert.Equal(t, []string{"b1", "b2", "b3", "b4"}, reloaded.Stacks[0].BranchNames())
}
// TestUpdateStack_BrokenChainAfterMerge verifies the "must form a stack" 422 is
// reported calmly when merged branches are present, but still warns otherwise.
func TestUpdateStack_BrokenChainAfterMerge(t *testing.T) {
mustFormErr := func() error {
return &api.HTTPError{
StatusCode: 422,
Message: "Pull requests must form a stack, where each PR's base ref is the previous PR's head ref",
RequestURL: &url.URL{Path: "/repos/o/r/stacks/42/add"},
}
}
t.Run("merged branches present is reported calmly", func(t *testing.T) {
s := &stack.Stack{
ID: "42",
Number: 42,
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 1, Merged: true}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 2}},
{Branch: "b3", PullRequest: &stack.PullRequestRef{Number: 3}},
},
}
mock := &github.MockClient{
GetStackFn: func(int) (*github.RemoteStack, error) {
return &github.RemoteStack{ID: 42, Number: 42, PullRequests: []int{1, 2}}, nil
},
AddToStackFn: func(int, []int) (*github.RemoteStack, error) { return nil, mustFormErr() },
}
cfg, _, errR := config.NewTestConfig()
updateStack(cfg, mock, s, []int{1, 2, 3})
cfg.Err.Close()
out, _ := io.ReadAll(errR)
output := string(out)
assert.Contains(t, output, "Merged PRs have left the stack")
assert.NotContains(t, output, "Failed to update stack")
})
t.Run("no merged branches still warns", func(t *testing.T) {
s := &stack.Stack{
ID: "42",
Number: 42,
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 1}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 2}},
},
}
mock := &github.MockClient{
GetStackFn: func(int) (*github.RemoteStack, error) {
return &github.RemoteStack{ID: 42, Number: 42, PullRequests: []int{1}}, nil
},
AddToStackFn: func(int, []int) (*github.RemoteStack, error) { return nil, mustFormErr() },
}
cfg, _, errR := config.NewTestConfig()
updateStack(cfg, mock, s, []int{1, 2})
cfg.Err.Close()
out, _ := io.ReadAll(errR)
output := string(out)
assert.Contains(t, output, "Failed to update stack")
})
}
func TestSubmit_DefaultPRTitleBody(t *testing.T) {
t.Run("single_commit", func(t *testing.T) {
restore := git.SetOps(&git.MockOps{
LogRangeFn: func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{
{Subject: "Add login page", Body: "Implements the OAuth flow"},
}, nil
},
})
defer restore()
title, body := defaultPRTitleBody("main", "feat-login")
assert.Equal(t, "Add login page", title)
assert.Equal(t, "Implements the OAuth flow", body)
})
t.Run("multiple_commits", func(t *testing.T) {
restore := git.SetOps(&git.MockOps{
LogRangeFn: func(base, head string) ([]git.CommitInfo, error) {
return []git.CommitInfo{
{Subject: "First commit"},
{Subject: "Second commit"},
}, nil
},
})
defer restore()
title, body := defaultPRTitleBody("main", "my-feature")
assert.Equal(t, "my feature", title)
assert.Equal(t, "", body)
})
}
func TestSubmit_Humanize(t *testing.T) {
tests := []struct {
input string
want string
}{
{"my-branch", "my branch"},
{"my_branch", "my branch"},
{"nobranch", "nobranch"},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
assert.Equal(t, tt.want, humanize(tt.input))
})
}
}
func TestSyncStack_NewStack_CreateSuccess(t *testing.T) {
s := &stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
},
}
var gotNumbers []int
mock := &github.MockClient{
CreateStackFn: func(prNumbers []int) (*github.RemoteStack, error) {
gotNumbers = prNumbers
return &github.RemoteStack{ID: 42, Number: 42}, nil
},
}
cfg, _, errR := config.NewTestConfig()
syncStack(cfg, mock, s)
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.Equal(t, []int{10, 11}, gotNumbers)
assert.Equal(t, "42", s.ID)
assert.Contains(t, output, "Stack created on GitHub with 2 PRs")
}
func TestSyncStack_ExistingStack_UpdateSuccess(t *testing.T) {
s := &stack.Stack{
ID: "99",
Number: 99,
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
{Branch: "b3", PullRequest: &stack.PullRequestRef{Number: 12}},
},
}
var gotStackNumber int
var gotNumbers []int
createCalled := false
mock := &github.MockClient{
CreateStackFn: func([]int) (*github.RemoteStack, error) {
createCalled = true
return &github.RemoteStack{ID: 0, Number: 0}, nil
},
GetStackFn: func(stackNumber int) (*github.RemoteStack, error) {
return &github.RemoteStack{ID: stackNumber, Number: stackNumber, PullRequests: []int{10, 11}}, nil
},
AddToStackFn: func(stackNumber int, prNumbers []int) (*github.RemoteStack, error) {
gotStackNumber = stackNumber
gotNumbers = prNumbers
return &github.RemoteStack{ID: 99, Number: 99, PullRequests: []int{10, 11, 12}}, nil
},
}
cfg, _, errR := config.NewTestConfig()
syncStack(cfg, mock, s)
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.False(t, createCalled, "CreateStack should not be called when s.ID is set")
assert.Equal(t, 99, gotStackNumber)
assert.Equal(t, []int{12}, gotNumbers)
assert.Contains(t, output, "Stack updated on GitHub with 3 PRs")
}
func TestSyncStack_ExistingStack_UpdateFails(t *testing.T) {
s := &stack.Stack{
ID: "99",
Number: 99,
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
},
}
mock := &github.MockClient{
GetStackFn: func(int) (*github.RemoteStack, error) {
return &github.RemoteStack{ID: 99, Number: 99, PullRequests: []int{10}}, nil
},
AddToStackFn: func(int, []int) (*github.RemoteStack, error) {
return nil, &api.HTTPError{
StatusCode: 422,
Message: "Validation failed",
RequestURL: &url.URL{Path: "/repos/o/r/stacks/99/add"},
}
},
}
cfg, _, errR := config.NewTestConfig()
syncStack(cfg, mock, s)
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.Contains(t, output, "Failed to update stack")
}
func TestSyncStack_ExistingStack_Update404(t *testing.T) {
s := &stack.Stack{
ID: "99",
Number: 99,
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
},
}
var createCalled bool
mock := &github.MockClient{
GetStackFn: func(int) (*github.RemoteStack, error) {
return &github.RemoteStack{ID: 99, Number: 99, PullRequests: []int{10}}, nil
},
AddToStackFn: func(int, []int) (*github.RemoteStack, error) {
return nil, &api.HTTPError{
StatusCode: 404,
Message: "Not Found",
RequestURL: &url.URL{Path: "/repos/o/r/stacks/99/add"},
}
},
CreateStackFn: func(prNumbers []int) (*github.RemoteStack, error) {
createCalled = true
return &github.RemoteStack{ID: 55, Number: 55}, nil
},
}
cfg, _, errR := config.NewTestConfig()
syncStack(cfg, mock, s)
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.True(t, createCalled, "should fall through to CreateStack after 404")
assert.Equal(t, "55", s.ID, "should set new stack ID from create response")
assert.Contains(t, output, "Stack created on GitHub with 2 PRs")
}
func TestSyncStack_AlreadyStacked_OurStack(t *testing.T) {
// All our PRs are listed as "already stacked" — this is our stack, show up-to-date.
s := &stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
},
}
mock := &github.MockClient{
CreateStackFn: func([]int) (*github.RemoteStack, error) {
return nil, &api.HTTPError{
StatusCode: 422,
Message: "Pull requests #10, #11 are already stacked",
RequestURL: &url.URL{Path: "/repos/o/r/stacks"},
}
},
}
cfg, _, errR := config.NewTestConfig()
syncStack(cfg, mock, s)
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.Contains(t, output, "Stack with 2 PRs is up to date")
assert.NotContains(t, output, "different stack")
}
func TestSyncStack_AlreadyStacked_DifferentStack(t *testing.T) {
// Only a subset of our PRs are listed — they're in a different stack.
s := &stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
{Branch: "b3", PullRequest: &stack.PullRequestRef{Number: 12}},
},
}
mock := &github.MockClient{
CreateStackFn: func([]int) (*github.RemoteStack, error) {
return nil, &api.HTTPError{
StatusCode: 422,
Message: "Pull requests #10, #11 are already stacked",
RequestURL: &url.URL{Path: "/repos/o/r/stacks"},
}
},
}
cfg, _, errR := config.NewTestConfig()
syncStack(cfg, mock, s)
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.Contains(t, output, "different stack")
assert.NotContains(t, output, "up to date")
}
func TestSyncStack_AdoptsExistingRemoteStack_ExactMatch(t *testing.T) {
// The stack exists on GitHub but isn't recorded locally (s.ID == "").
// All local PRs match the remote stack exactly — adopt the ID without
// creating or updating anything.
s := &stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
},
}
var createCalled, updateCalled bool
mock := &github.MockClient{
ListStacksFn: func() ([]github.RemoteStack, error) {
return []github.RemoteStack{{ID: 77, Number: 77, PullRequests: []int{10, 11}}}, nil
},
CreateStackFn: func([]int) (*github.RemoteStack, error) {
createCalled = true
return &github.RemoteStack{ID: 0, Number: 0}, nil
},
AddToStackFn: func(int, []int) (*github.RemoteStack, error) {
updateCalled = true
return &github.RemoteStack{ID: 77, Number: 77, PullRequests: []int{10, 11}}, nil
},
}
cfg, _, errR := config.NewTestConfig()
syncStack(cfg, mock, s)
cfg.Err.Close()
errOut, _ := io.ReadAll(errR)
output := string(errOut)
assert.False(t, createCalled, "should not create when the stack already exists on GitHub")
assert.False(t, updateCalled, "should not update when local matches remote exactly")
assert.Equal(t, "77", s.ID, "should adopt the remote stack ID into local tracking")
assert.Contains(t, output, "Linked to the existing stack on GitHub")
assert.Contains(t, output, "up to date")
}
func TestSyncStack_AdoptsExistingRemoteStack_AddsNewPR(t *testing.T) {
// Two of our three PRs already form a remote stack; the third was added
// locally on top. Adopt the remote ID and update the stack to include the
// new PR at the top.
s := &stack.Stack{
Trunk: stack.BranchRef{Branch: "main"},
Branches: []stack.BranchRef{
{Branch: "b1", PullRequest: &stack.PullRequestRef{Number: 10}},
{Branch: "b2", PullRequest: &stack.PullRequestRef{Number: 11}},
{Branch: "b3", PullRequest: &stack.PullRequestRef{Number: 12}},
},