Repository navigation
Expand file tree
/
Copy pathclient_test.go
More file actions
2084 lines (1747 loc) · 68.6 KB
/
Copy pathclient_test.go
File metadata and controls
2084 lines (1747 loc) · 68.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 git
import (
"bytes"
"context"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClientCommand(t *testing.T) {
tests := []struct {
name string
repoDir string
gitPath string
wantExe string
wantArgs []string
}{
{
name: "creates command",
gitPath: "path/to/git",
wantExe: "path/to/git",
wantArgs: []string{"path/to/git", "ref-log"},
},
{
name: "adds repo directory configuration",
repoDir: "path/to/repo",
gitPath: "path/to/git",
wantExe: "path/to/git",
wantArgs: []string{"path/to/git", "-C", "path/to/repo", "ref-log"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Given a client with explicit executable, streams, and repository context
in, out, errOut := &bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{}
client := Client{
Stdin: in,
Stdout: out,
Stderr: errOut,
RepoDir: tt.repoDir,
GitPath: tt.gitPath,
}
// When a Git command is created
cmd, err := client.Command(t.Context(), "ref-log")
// Then the executable, repository arguments, and streams are wired
require.NoError(t, err)
assert.Equal(t, tt.wantExe, cmd.Path)
assert.Equal(t, tt.wantArgs, cmd.Args)
assert.Same(t, in, cmd.Stdin)
assert.Same(t, out, cmd.Stdout)
assert.Same(t, errOut, cmd.Stderr)
})
}
}
func TestClientAuthenticatedCommandScopesCredentialHelperToAllHosts(t *testing.T) {
// Given a client with an explicit gh executable
client := Client{
GhPath: "path/to/gh",
GitPath: "path/to/git",
}
// When an authenticated command is created for all hosts
cmd, err := client.AuthenticatedCommand(t.Context(), AllMatchingCredentialsPattern, "fetch")
// Then existing helpers are cleared and gh receives credentials for every host
require.NoError(t, err)
assert.Equal(t, []string{"path/to/git", "-c", "credential.helper=", "-c", `credential.helper=!"path/to/gh" auth git-credential`, "fetch"}, cmd.Args)
}
func TestClientAuthenticatedCommandScopesCredentialHelperToPattern(t *testing.T) {
// Given a client with an explicit gh executable
client := Client{
GhPath: "path/to/gh",
GitPath: "path/to/git",
}
// When an authenticated command is created for one credential pattern
cmd, err := client.AuthenticatedCommand(t.Context(), CredentialPattern{pattern: "https://github.com"}, "fetch")
// Then existing helpers are cleared and gh receives credentials only for that pattern
require.NoError(t, err)
assert.Equal(t, []string{"path/to/git", "-c", "credential.https://github.com.helper=", "-c", `credential.https://github.com.helper=!"path/to/gh" auth git-credential`, "fetch"}, cmd.Args)
}
func TestClientAuthenticatedCommandDefaultsToGhOnPath(t *testing.T) {
// Given a client without an explicit gh executable
client := Client{GitPath: "path/to/git"}
// When an authenticated command is created
cmd, err := client.AuthenticatedCommand(t.Context(), AllMatchingCredentialsPattern, "fetch")
// Then gh is resolved from PATH by the credential helper
require.NoError(t, err)
assert.Equal(t, []string{"path/to/git", "-c", "credential.helper=", "-c", `credential.helper=!"gh" auth git-credential`, "fetch"}, cmd.Args)
}
func TestClientAuthenticatedCommandRejectsEmptyCredentialPattern(t *testing.T) {
// Given a client and an empty host-scoped credential pattern
client := Client{GitPath: "path/to/git"}
// When an authenticated command is created
cmd, err := client.AuthenticatedCommand(t.Context(), CredentialPattern{}, "fetch")
// Then the insecure ambiguous scope is rejected
require.EqualError(t, err, "empty credential pattern is not allowed unless provided explicitly")
assert.Nil(t, cmd)
}
func TestClientRemotesReturnsSortedRemotesWithResolutions(t *testing.T) {
// Given remotes with resolution metadata
repo := newTestRepo(t)
repo.run(t, "remote", "add", "origin", "git@example.com:monalisa/origin.git")
repo.run(t, "remote", "add", "test", "git://github.com/hubot/test.git")
repo.run(t, "remote", "add", "upstream", "https://github.com/monalisa/upstream.git")
repo.run(t, "remote", "add", "github", "git@github.com:hubot/github.git")
repo.run(t, "config", "remote.test.gh-resolved", "other")
repo.run(t, "config", "remote.upstream.gh-resolved", "base")
// When the remotes are listed
remotes, err := repo.client.Remotes(t.Context())
// Then preferred names are sorted first and resolutions are associated by name
require.NoError(t, err)
require.Len(t, remotes, 4)
assert.Equal(t, "upstream", remotes[0].Name)
assert.Equal(t, "base", remotes[0].Resolved)
assert.Equal(t, "github", remotes[1].Name)
assert.Empty(t, remotes[1].Resolved)
assert.Equal(t, "origin", remotes[2].Name)
assert.Empty(t, remotes[2].Resolved)
assert.Equal(t, "test", remotes[3].Name)
assert.Equal(t, "other", remotes[3].Resolved)
}
func TestClientRemotesToleratesMissingResolutionConfig(t *testing.T) {
// Given a remote without resolution metadata
repo := newTestRepo(t)
repo.run(t, "remote", "add", "origin", "git@example.com:monalisa/origin.git")
// When the remotes are listed
remotes, err := repo.client.Remotes(t.Context())
// Then Git's no-matching-config status is treated as an empty resolution
require.NoError(t, err)
require.Len(t, remotes, 1)
assert.Equal(t, "origin", remotes[0].Name)
assert.Empty(t, remotes[0].Resolved)
}
func TestParseRemotes(t *testing.T) {
// Given remote output with fetch-only, push-only, paired, and mixed URL forms
remoteList := []string{
"mona\tgit@github.com:monalisa/myfork.git (fetch)",
"origin\thttps://github.com/monalisa/octo-cat.git (fetch)",
"origin\thttps://github.com/monalisa/octo-cat-push.git (push)",
"upstream\thttps://example.com/nowhere.git (fetch)",
"upstream\thttps://github.com/hubot/tools (push)",
"zardoz\thttps://example.com/zed.git (push)",
"koke\tgit://github.com/koke/grit.git (fetch)",
"koke\tgit://github.com/koke/grit.git (push)",
}
// When the output is parsed
remotes := parseRemotes(remoteList)
// Then each URL is associated with its named remote and direction
require.Len(t, remotes, 5)
assert.Equal(t, "mona", remotes[0].Name)
assert.Equal(t, "ssh://git@github.com/monalisa/myfork.git", remotes[0].FetchURL.String())
assert.Nil(t, remotes[0].PushURL)
assert.Equal(t, "origin", remotes[1].Name)
assert.Equal(t, "/monalisa/octo-cat.git", remotes[1].FetchURL.Path)
assert.Equal(t, "/monalisa/octo-cat-push.git", remotes[1].PushURL.Path)
assert.Equal(t, "upstream", remotes[2].Name)
assert.Equal(t, "example.com", remotes[2].FetchURL.Host)
assert.Equal(t, "github.com", remotes[2].PushURL.Host)
assert.Equal(t, "zardoz", remotes[3].Name)
assert.Nil(t, remotes[3].FetchURL)
assert.Equal(t, "https://example.com/zed.git", remotes[3].PushURL.String())
assert.Equal(t, "koke", remotes[4].Name)
assert.Equal(t, "/koke/grit.git", remotes[4].FetchURL.Path)
assert.Equal(t, "/koke/grit.git", remotes[4].PushURL.Path)
}
func TestClientUpdateRemoteURLUpdatesConfiguredRemote(t *testing.T) {
// Given a repository with a local remote
repo := newTestRepo(t)
original := newBareTestRepo(t)
replacement := newBareTestRepo(t)
repo.run(t, "remote", "add", "test", original.fileURL())
// When the remote URL is updated
err := repo.client.UpdateRemoteURL(t.Context(), "test", replacement.fileURL())
// Then Git stores the replacement URL
require.NoError(t, err)
assert.Equal(t, replacement.fileURL(), repo.run(t, "remote", "get-url", "test"))
}
func TestClientUpdateRemoteURLReportsMissingRemote(t *testing.T) {
// Given a repository without the named remote
repo := newTestRepo(t)
// When the remote URL is updated
err := repo.client.UpdateRemoteURL(t.Context(), "missing", newBareTestRepo(t).fileURL())
// Then Git reports a semantic command failure
require.Error(t, err)
var gitErr *GitError
require.ErrorAs(t, err, &gitErr)
assert.NotZero(t, gitErr.ExitCode)
}
func TestClientSetRemoteResolutionAddsResolution(t *testing.T) {
// Given a repository with an existing remote resolution
repo := newTestRepo(t)
repo.run(t, "config", "--add", "remote.origin.gh-resolved", "base")
// When another resolution is set
err := repo.client.SetRemoteResolution(t.Context(), "origin", "other")
// Then both resolutions are stored
require.NoError(t, err)
assert.Equal(t, "base\nother", repo.run(t, "config", "--get-all", "remote.origin.gh-resolved"))
}
func TestClientSetRemoteResolutionPropagatesGitError(t *testing.T) {
// Given a client whose repository directory does not exist
client := Client{RepoDir: filepath.Join(t.TempDir(), "missing")}
// When a remote resolution is set
err := client.SetRemoteResolution(t.Context(), "origin", "base")
// Then the Git error is returned
require.Error(t, err)
var gitErr *GitError
require.ErrorAs(t, err, &gitErr)
assert.NotZero(t, gitErr.ExitCode)
}
func TestClientCurrentBranchReturnsCurrentBranch(t *testing.T) {
// Given a repository checked out on a branch containing non-breaking spaces
repo := newTestRepo(t)
branchName := "branch\u00A0with\u00A0non\u00A0breaking\u00A0space"
repo.run(t, "checkout", "--quiet", "-b", branchName)
// When the current branch is requested
branch, err := repo.client.CurrentBranch(t.Context())
// Then the complete branch name is returned
require.NoError(t, err)
assert.Equal(t, branchName, branch)
}
func TestClientCurrentBranchReportsDetachedHead(t *testing.T) {
// Given a repository with a detached HEAD
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
repo.run(t, "checkout", "--quiet", "--detach")
// When the current branch is requested
branch, err := repo.client.CurrentBranch(t.Context())
// Then the detached HEAD error is returned
require.Error(t, err)
assert.ErrorIs(t, err, ErrNotOnAnyBranch)
assert.Empty(t, branch)
}
func TestClientShowRefsReturnsExistingRefsAlongsideMissingRefError(t *testing.T) {
// Given a repository with one requested branch and one missing branch
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
wantHash := repo.run(t, "rev-parse", "HEAD")
// When both refs are resolved
refs, err := repo.client.ShowRefs(t.Context(), []string{"refs/heads/trunk", "refs/heads/missing"})
// Then the existing ref and the semantic Git error are both returned
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.NotZero(t, gitError.ExitCode)
assert.Equal(t, []Ref{{Hash: wantHash, Name: "refs/heads/trunk"}}, refs)
}
func TestClientShowRefsSeparatesRefsFromOptions(t *testing.T) {
// Given a repository with one branch
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
wantHash := repo.run(t, "rev-parse", "HEAD")
// When the branch and an option-like ref are resolved
refs, err := repo.client.ShowRefs(t.Context(), []string{"refs/heads/trunk", "--quiet"})
// Then an option separator protects the refs, so the branch resolves and the option-like ref is rejected
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.NotZero(t, gitError.ExitCode)
assert.Equal(t, []Ref{{Hash: wantHash, Name: "refs/heads/trunk"}}, refs)
}
func TestClientConfigReturnsConfiguredValue(t *testing.T) {
// Given a repository with a configured credential helper
repo := newTestRepo(t)
repo.run(t, "config", "credential.helper", "test")
// When the configuration is read
value, err := repo.client.Config(t.Context(), "credential.helper")
// Then the configured value is returned
require.NoError(t, err)
assert.Equal(t, "test", value)
}
func TestClientConfigReportsUnknownKey(t *testing.T) {
// Given a repository without a credential helper
repo := newTestRepo(t)
// When the missing configuration is read
value, err := repo.client.Config(t.Context(), "credential.helper")
// Then the missing key is identified
require.Error(t, err)
assert.EqualError(t, err, "failed to run git: unknown config key credential.helper")
assert.Empty(t, value)
}
func TestClientConfigPropagatesGitError(t *testing.T) {
// Given a client whose repository directory does not exist
client := Client{RepoDir: filepath.Join(t.TempDir(), "missing")}
// When configuration is read
value, err := client.Config(t.Context(), "credential.helper")
// Then the Git error is returned unchanged
require.Error(t, err)
var gitErr *GitError
require.ErrorAs(t, err, &gitErr)
assert.NotZero(t, gitErr.ExitCode)
assert.Contains(t, gitErr.Stderr, client.RepoDir)
assert.Empty(t, value)
}
func TestClientUncommittedChangeCountReturnsZeroForCleanRepository(t *testing.T) {
// Given a clean repository
repo := newTestRepo(t)
// When uncommitted changes are counted
count, err := repo.client.UncommittedChangeCount(t.Context())
// Then no changes are reported
require.NoError(t, err)
assert.Equal(t, 0, count)
}
func TestClientUncommittedChangeCountIncludesTrackedAndUntrackedFiles(t *testing.T) {
// Given a repository with one modified file and one untracked file
repo := newTestRepo(t)
trackedFile := filepath.Join(repo.dir, "tracked.txt")
require.NoError(t, os.WriteFile(trackedFile, []byte("tracked\n"), 0600))
repo.run(t, "add", "tracked.txt")
repo.run(t, "commit", "--quiet", "-m", "add tracked file")
require.NoError(t, os.WriteFile(trackedFile, []byte("modified\n"), 0600))
require.NoError(t, os.WriteFile(filepath.Join(repo.dir, "untracked.txt"), []byte("untracked\n"), 0600))
// When uncommitted changes are counted
count, err := repo.client.UncommittedChangeCount(t.Context())
// Then both changes are reported
require.NoError(t, err)
assert.Equal(t, 2, count)
}
func TestClientCommitsReturnsCommitMetadata(t *testing.T) {
// Given a branch with commits containing empty and multiline bodies
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "base")
baseRef := repo.run(t, "rev-parse", "HEAD")
repo.run(t, "checkout", "--quiet", "-b", "feature")
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "first commit")
firstSHA := repo.run(t, "rev-parse", "HEAD")
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "second commit", "-m", "first line\nsecond line")
secondSHA := repo.run(t, "rev-parse", "HEAD")
// When commits unique to the feature branch are requested
commits, err := repo.client.Commits(t.Context(), baseRef, "feature")
// Then each commit's repository metadata is returned newest first
require.NoError(t, err)
assert.Equal(t, []*Commit{
{Sha: secondSHA, Title: "second commit", Body: "first line\nsecond line\n"},
{Sha: firstSHA, Title: "first commit"},
}, commits)
}
func TestClientCommitsReportsNoCommitsBetweenRefs(t *testing.T) {
// Given two refs that identify the same commit
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
// When commits between the refs are requested
commits, err := repo.client.Commits(t.Context(), "trunk", "trunk")
// Then the empty comparison is reported
require.EqualError(t, err, "could not find any commits between trunk and trunk")
assert.Nil(t, commits)
}
func TestClientCommitsExcludesBaseSideCommits(t *testing.T) {
// Given divergent branches with patch-equivalent commits and one unique feature commit
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
repo.run(t, "checkout", "--quiet", "-b", "feature")
require.NoError(t, os.WriteFile(filepath.Join(repo.dir, "shared.txt"), []byte("shared\n"), 0600))
repo.run(t, "add", "shared.txt")
t.Setenv("GIT_COMMITTER_DATE", "2000-01-01T00:00:00Z")
repo.run(t, "commit", "--quiet", "-m", "feature shared change")
sharedCommit := repo.run(t, "rev-parse", "HEAD")
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "feature-only commit")
uniqueCommit := repo.run(t, "rev-parse", "HEAD")
repo.run(t, "checkout", "--quiet", "trunk")
// A different committer date gives the cherry-picked commit a distinct hash.
t.Setenv("GIT_COMMITTER_DATE", "2001-01-01T00:00:00Z")
repo.run(t, "cherry-pick", sharedCommit)
// When commits unique to the feature branch are requested
commits, err := repo.client.Commits(t.Context(), "trunk", "feature")
// Then only the feature side of the symmetric difference is returned
require.NoError(t, err)
assert.Equal(t, []*Commit{
{Sha: uniqueCommit, Title: "feature-only commit"},
{Sha: sharedCommit, Title: "feature shared change"},
}, commits)
}
func TestClientCommitsReturnsOnlyOrdinaryFeatureSideCommits(t *testing.T) {
// Given a feature branch that merges a side branch
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
repo.run(t, "checkout", "--quiet", "-b", "feature")
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "feature work")
featureSHA := repo.run(t, "rev-parse", "HEAD")
repo.run(t, "checkout", "--quiet", "-b", "side", "trunk")
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "side work")
sideSHA := repo.run(t, "rev-parse", "HEAD")
repo.run(t, "checkout", "--quiet", "feature")
repo.run(t, "merge", "--no-ff", "side", "-m", "merge side")
// When commits unique to the feature branch are requested
commits, err := repo.client.Commits(t.Context(), "trunk", "feature")
// Then the merge commit is excluded and both ordinary feature-side commits are returned
require.NoError(t, err)
assert.ElementsMatch(t, []*Commit{
{Sha: featureSHA, Title: "feature work"},
{Sha: sideSHA, Title: "side work"},
}, commits)
}
func TestClientCommitsReportsInvalidRef(t *testing.T) {
// Given a repository without the requested head ref
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
// When commits for the missing ref are requested
commits, err := repo.client.Commits(t.Context(), "trunk", "missing")
// Then Git's invalid revision error is returned
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.NotZero(t, gitError.ExitCode)
assert.Contains(t, gitError.Stderr, "trunk...missing")
assert.Nil(t, commits)
}
func TestClientLastCommit(t *testing.T) {
// Given a repository fixture with two commits
IsolateConfig(t)
client := Client{RepoDir: "./fixtures/simple.git"}
// When its last commit is requested
commit, err := client.LastCommit(t.Context())
// Then the commit identity and title are returned
require.NoError(t, err)
assert.Equal(t, "6f1a2405cace1633d89a79c74c65f22fe78f9659", commit.Sha)
assert.Equal(t, "Second commit", commit.Title)
}
func TestClientCommitBody(t *testing.T) {
// Given a repository fixture with a commit body
IsolateConfig(t)
client := Client{RepoDir: "./fixtures/simple.git"}
// When the body is requested
body, err := client.CommitBody(t.Context(), "6f1a2405cace1633d89a79c74c65f22fe78f9659")
// Then the complete body is returned
require.NoError(t, err)
assert.Equal(t, "I'm starting to get the hang of things\n", body)
}
func TestClientReadBranchConfigReturnsEmptyConfigWhenUnset(t *testing.T) {
// Given a repository without branch configuration
repo := newTestRepo(t)
// When the branch configuration is read
branchConfig, err := repo.client.ReadBranchConfig(t.Context(), "trunk")
// Then an empty configuration is returned without error
require.NoError(t, err)
assert.Equal(t, BranchConfig{}, branchConfig)
}
func TestClientReadBranchConfigReturnsConfiguredValues(t *testing.T) {
// Given all supported branch configuration values set through the client
repo := newTestRepo(t)
require.NoError(t, repo.client.SetBranchConfig(t.Context(), "trunk", "remote", "upstream"))
require.NoError(t, repo.client.SetBranchConfig(t.Context(), "trunk", "merge", "refs/heads/trunk"))
require.NoError(t, repo.client.SetBranchConfig(t.Context(), "trunk", "pushremote", "origin"))
require.NoError(t, repo.client.SetBranchConfig(t.Context(), "trunk", MergeBaseConfig, "release"))
// When the branch configuration is read
branchConfig, err := repo.client.ReadBranchConfig(t.Context(), "trunk")
// Then the persisted configuration is returned
require.NoError(t, err)
assert.Equal(t, BranchConfig{
RemoteName: "upstream",
PushRemoteName: "origin",
MergeRef: "refs/heads/trunk",
MergeBase: "release",
}, branchConfig)
}
func TestClientReadBranchConfigPropagatesGitError(t *testing.T) {
// Given a client whose repository directory no longer exists
repo := newTestRepo(t)
require.NoError(t, os.RemoveAll(repo.dir))
// When branch configuration is read
branchConfig, err := repo.client.ReadBranchConfig(t.Context(), "trunk")
// Then the repository error is preserved
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.Equal(t, 128, gitError.ExitCode)
assert.Empty(t, branchConfig)
}
func TestParseBranchConfig(t *testing.T) {
tests := []struct {
name string
configLines []string
wantBranchConfig BranchConfig
}{
{
name: "remote branch",
configLines: []string{"branch.trunk.remote origin"},
wantBranchConfig: BranchConfig{
RemoteName: "origin",
},
},
{
name: "merge ref",
configLines: []string{"branch.trunk.merge refs/heads/trunk"},
wantBranchConfig: BranchConfig{
MergeRef: "refs/heads/trunk",
},
},
{
name: "merge base",
configLines: []string{"branch.trunk.gh-merge-base gh-merge-base"},
wantBranchConfig: BranchConfig{
MergeBase: "gh-merge-base",
},
},
{
name: "pushremote",
configLines: []string{"branch.trunk.pushremote pushremote"},
wantBranchConfig: BranchConfig{
PushRemoteName: "pushremote",
},
},
{
name: "remote and pushremote are specified by name",
configLines: []string{
"branch.trunk.remote upstream",
"branch.trunk.pushremote origin",
},
wantBranchConfig: BranchConfig{
RemoteName: "upstream",
PushRemoteName: "origin",
},
},
{
name: "remote and pushremote are specified by url",
configLines: []string{
"branch.trunk.remote git@github.com:UPSTREAMOWNER/REPO.git",
"branch.trunk.pushremote git@github.com:ORIGINOWNER/REPO.git",
},
wantBranchConfig: BranchConfig{
RemoteURL: &url.URL{
Scheme: "ssh",
User: url.User("git"),
Host: "github.com",
Path: "/UPSTREAMOWNER/REPO.git",
},
PushRemoteURL: &url.URL{
Scheme: "ssh",
User: url.User("git"),
Host: "github.com",
Path: "/ORIGINOWNER/REPO.git",
},
},
},
{
name: "remote, pushremote, gh-merge-base, and merge ref all specified",
configLines: []string{
"branch.trunk.remote remote",
"branch.trunk.pushremote pushremote",
"branch.trunk.gh-merge-base gh-merge-base",
"branch.trunk.merge refs/heads/trunk",
},
wantBranchConfig: BranchConfig{
RemoteName: "remote",
PushRemoteName: "pushremote",
MergeBase: "gh-merge-base",
MergeRef: "refs/heads/trunk",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Given branch configuration output
configLines := tt.configLines
// When the output is parsed
branchConfig := parseBranchConfig(configLines)
// Then each supported key is mapped to its typed field
assert.Equal(t, tt.wantBranchConfig, branchConfig)
})
}
}
func TestParseRemoteURLOrName(t *testing.T) {
tests := []struct {
name string
value string
wantRemoteURL *url.URL
wantRemoteName string
}{
{
name: "empty value",
value: "",
wantRemoteURL: nil,
wantRemoteName: "",
},
{
name: "remote URL",
value: "git@github.com:foo/bar.git",
wantRemoteURL: &url.URL{
Scheme: "ssh",
User: url.User("git"),
Host: "github.com",
Path: "/foo/bar.git",
},
wantRemoteName: "",
},
{
name: "remote name",
value: "origin",
wantRemoteURL: nil,
wantRemoteName: "origin",
},
{
name: "remote name is from filesystem",
value: "./path/to/repo",
wantRemoteURL: nil,
wantRemoteName: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Given a configured branch remote value
value := tt.value
// When it is classified
remoteURL, remoteName := parseRemoteURLOrName(value)
// Then URLs and names are returned through their distinct fields
assert.Equal(t, tt.wantRemoteURL, remoteURL)
assert.Equal(t, tt.wantRemoteName, remoteName)
})
}
}
func TestClientPushDefaultReturnsGitDefaultWhenUnset(t *testing.T) {
// Given a repository without push.default
repo := newTestRepo(t)
// When push.default is read
pushDefault, err := repo.client.PushDefault(t.Context())
// Then Git's default behavior is returned
require.NoError(t, err)
assert.Equal(t, PushDefaultSimple, pushDefault)
}
func TestClientPushDefaultReturnsConfiguredValue(t *testing.T) {
// Given a repository configured to push the current branch
repo := newTestRepo(t)
repo.run(t, "config", "push.default", "current")
// When push.default is read
pushDefault, err := repo.client.PushDefault(t.Context())
// Then the configured behavior is returned
require.NoError(t, err)
assert.Equal(t, PushDefaultCurrent, pushDefault)
}
func TestClientPushDefaultPropagatesGitError(t *testing.T) {
// Given a client whose repository directory no longer exists
repo := newTestRepo(t)
require.NoError(t, os.RemoveAll(repo.dir))
// When push.default is read
pushDefault, err := repo.client.PushDefault(t.Context())
// Then the repository error is preserved
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.Equal(t, 128, gitError.ExitCode)
assert.Empty(t, pushDefault)
}
func TestClientRemotePushDefaultReturnsEmptyWhenUnset(t *testing.T) {
// Given a repository without remote.pushDefault
repo := newTestRepo(t)
// When remote.pushDefault is read
remote, err := repo.client.RemotePushDefault(t.Context())
// Then no preferred remote is returned
require.NoError(t, err)
assert.Empty(t, remote)
}
func TestClientRemotePushDefaultReturnsConfiguredRemote(t *testing.T) {
// Given a repository with a preferred push remote
repo := newTestRepo(t)
repo.run(t, "config", "remote.pushDefault", "origin")
// When remote.pushDefault is read
remote, err := repo.client.RemotePushDefault(t.Context())
// Then the configured remote is returned
require.NoError(t, err)
assert.Equal(t, "origin", remote)
}
func TestClientRemotePushDefaultPropagatesGitError(t *testing.T) {
// Given a client whose repository directory no longer exists
repo := newTestRepo(t)
require.NoError(t, os.RemoveAll(repo.dir))
// When remote.pushDefault is read
remote, err := repo.client.RemotePushDefault(t.Context())
// Then the repository error is preserved
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.Equal(t, 128, gitError.ExitCode)
assert.Empty(t, remote)
}
func TestClientPushRevisionReturnsPushRemoteTrackingRef(t *testing.T) {
// Given a branch that fetches from upstream but pushes to origin
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
repo.run(t, "remote", "add", "upstream", filepath.Join(t.TempDir(), "upstream.git"))
repo.run(t, "remote", "add", "origin", filepath.Join(t.TempDir(), "remote.git"))
repo.run(t, "config", "branch.trunk.remote", "upstream")
repo.run(t, "config", "branch.trunk.merge", "refs/heads/main")
repo.run(t, "config", "branch.trunk.pushremote", "origin")
repo.run(t, "config", "push.default", "current")
repo.run(t, "update-ref", "refs/remotes/upstream/main", "HEAD")
repo.run(t, "update-ref", "refs/remotes/origin/trunk", "HEAD")
// When the branch's push revision is resolved
trackingRef, err := repo.client.PushRevision(t.Context(), "trunk")
// Then the push remote's current-branch tracking ref is returned rather than the upstream's
require.NoError(t, err)
assert.Equal(t, RemoteTrackingRef{Remote: "origin", Branch: "trunk"}, trackingRef)
}
func TestClientPushRevisionReportsUnresolvedBranch(t *testing.T) {
// Given a repository without the requested branch
repo := newTestRepo(t)
// When its push revision is resolved
trackingRef, err := repo.client.PushRevision(t.Context(), "missing")
// Then Git's revision error is returned
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.NotZero(t, gitError.ExitCode)
assert.Empty(t, trackingRef)
}
func TestParsePushRevisionReportsMalformedSymbolicRef(t *testing.T) {
// Given Git returns a symbolic push ref outside refs/remotes
output := []byte("not/a/valid/remote/ref")
// When the push revision is parsed
trackingRef, err := parsePushRevision(output)
// Then the malformed ref is reported with context
require.EqualError(t, err, "could not parse push revision: remote tracking branch must have format refs/remotes/<remote>/<branch> but was: not/a/valid/remote/ref")
assert.Empty(t, trackingRef)
}
func TestParseRemoteTrackingRef(t *testing.T) {
tests := []struct {
name string
ref string
want RemoteTrackingRef
}{
{
name: "branch without slash",
ref: "refs/remotes/origin/branchName",
want: RemoteTrackingRef{Remote: "origin", Branch: "branchName"},
},
{
name: "branch with slash",
ref: "refs/remotes/origin/branch/name",
want: RemoteTrackingRef{Remote: "origin", Branch: "branch/name"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Given a qualified remote-tracking ref
ref := tt.ref
// When it is parsed
trackingRef, err := ParseRemoteTrackingRef(ref)
// Then the remote and complete branch name are returned
require.NoError(t, err)
assert.Equal(t, tt.want, trackingRef)
})
}
}
func TestParseRemoteTrackingRefReportsMalformedInput(t *testing.T) {
tests := []struct {
name string
ref string
}{
{name: "missing branch", ref: "refs/remotes/origin"},
{name: "incorrect refs prefix", ref: "invalid/remotes/origin/branchName"},
{name: "incorrect ref type", ref: "refs/invalid/origin/branchName"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Given a string outside the remote-tracking ref grammar
ref := tt.ref
// When it is parsed
trackingRef, err := ParseRemoteTrackingRef(ref)
// Then the invalid value is included in the format diagnostic
require.EqualError(t, err, "remote tracking branch must have format refs/remotes/<remote>/<branch> but was: "+ref)
assert.Empty(t, trackingRef)
})
}
}
func TestRemoteTrackingRefString(t *testing.T) {
// Given a remote and branch name
trackingRef := RemoteTrackingRef{Remote: "origin", Branch: "branchName"}
// When the tracking ref is formatted
ref := trackingRef.String()
// Then a qualified remote-tracking ref is returned
assert.Equal(t, "refs/remotes/origin/branchName", ref)
}
func TestClientDeleteLocalTagRemovesTag(t *testing.T) {
// Given a repository with a local tag
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
repo.run(t, "tag", "v1.0")
// When the tag is deleted
err := repo.client.DeleteLocalTag(t.Context(), "v1.0")
// Then the tag no longer resolves
require.NoError(t, err)
assert.Empty(t, repo.run(t, "tag", "--list", "v1.0"))
}
func TestClientDeleteLocalTagReportsMissingTag(t *testing.T) {
// Given a repository without the requested tag
repo := newTestRepo(t)
// When the missing tag is deleted
err := repo.client.DeleteLocalTag(t.Context(), "missing")
// Then Git's missing tag error is returned
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.NotZero(t, gitError.ExitCode)
}
func TestClientDeleteLocalBranchRemovesUnmergedBranch(t *testing.T) {
// Given a feature branch with a commit that is not merged into trunk
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
repo.run(t, "checkout", "--quiet", "-b", "feature")
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "unmerged feature work")
repo.run(t, "checkout", "--quiet", "trunk")
// When the branch is deleted
err := repo.client.DeleteLocalBranch(t.Context(), "feature")
// Then the branch no longer exists
require.NoError(t, err)
assert.False(t, repo.client.HasLocalBranch(t.Context(), "feature"), "deleted branch should not resolve")
}
func TestClientDeleteLocalBranchReportsCheckedOutBranch(t *testing.T) {
// Given a repository whose trunk branch is checked out
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
// When the checked out branch is deleted
err := repo.client.DeleteLocalBranch(t.Context(), "trunk")
// Then Git rejects the deletion and the branch remains
require.Error(t, err)
var gitError *GitError
require.ErrorAs(t, err, &gitError)
assert.NotZero(t, gitError.ExitCode)
assert.True(t, repo.client.HasLocalBranch(t.Context(), "trunk"), "checked out branch should remain")
}
func TestClientHasLocalBranchFindsExistingBranch(t *testing.T) {
// Given a repository with a trunk commit
repo := newTestRepo(t)
repo.run(t, "commit", "--quiet", "--allow-empty", "-m", "initial commit")
// When the local branch is checked
exists := repo.client.HasLocalBranch(t.Context(), "trunk")
// Then the branch is found
assert.True(t, exists, "trunk should resolve as a local branch")
}
func TestClientHasLocalBranchRejectsMissingBranch(t *testing.T) {
// Given a repository without a feature branch
repo := newTestRepo(t)
// When the local branch is checked
exists := repo.client.HasLocalBranch(t.Context(), "feature")
// Then the branch is not found
assert.False(t, exists, "missing branch should not resolve")