{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrepository_test.go
More file actions
4499 lines (3710 loc) · 115 KB
/
Copy pathrepository_test.go
File metadata and controls
4499 lines (3710 loc) · 115 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 (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
"time"
"github.com/go-git/go-billy/v6"
"github.com/go-git/go-billy/v6/memfs"
"github.com/go-git/go-billy/v6/osfs"
"github.com/go-git/go-billy/v6/util"
fixtures "github.com/go-git/go-git-fixtures/v6"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/go-git/go-git/v6/config"
archivePkg "github.com/go-git/go-git/v6/internal/archive"
"github.com/go-git/go-git/v6/internal/server"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/cache"
formatcfg "github.com/go-git/go-git/v6/plumbing/format/config"
"github.com/go-git/go-git/v6/plumbing/object"
"github.com/go-git/go-git/v6/plumbing/protocol/packp"
"github.com/go-git/go-git/v6/plumbing/storer"
"github.com/go-git/go-git/v6/plumbing/transport"
"github.com/go-git/go-git/v6/storage"
"github.com/go-git/go-git/v6/storage/filesystem"
"github.com/go-git/go-git/v6/storage/memory"
"github.com/go-git/go-git/v6/x/plugin"
xstorage "github.com/go-git/go-git/v6/x/storage"
)
func TestInit(t *testing.T) {
t.Parallel()
tests := []struct {
name string
opts func() []InitOption
wantBare bool
wantBranch string
}{
{
name: "Bare",
opts: func() []InitOption { return []InitOption{} },
wantBare: true,
},
{
name: "With Worktree",
opts: func() []InitOption {
return []InitOption{WithWorkTree(memfs.New())}
},
},
{
name: "With Default Branch",
opts: func() []InitOption {
return []InitOption{
WithWorkTree(memfs.New()),
WithDefaultBranch("refs/head/foo"),
}
},
wantBranch: "refs/head/foo",
},
}
forEachFormat(t, func(t *testing.T, of formatcfg.ObjectFormat) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
opts := append(tc.opts(), WithObjectFormat(of))
r, err := Init(memory.NewStorage(memory.WithObjectFormat(of)), opts...)
require.NotNil(t, r)
require.NoError(t, err)
defer func() { _ = r.Close() }()
cfg, err := r.Config()
require.NoError(t, err)
assert.Equal(t, tc.wantBare, cfg.Core.IsBare)
assert.Equal(t, of, cfg.Extensions.ObjectFormat, "object format mismatch")
if !tc.wantBare {
h := createCommit(t, r)
assert.Equal(t, of.HexSize(), len(h.String()))
wantBranch := tc.wantBranch
if wantBranch == "" {
wantBranch = plumbing.Master.String()
}
ref, err := r.Head()
require.NoError(t, err)
require.Equal(t, wantBranch, ref.Name().String())
}
})
}
})
}
func TestPlainInitAndPlainOpen(t *testing.T) {
t.Parallel()
tests := []struct {
name string
opts func() []InitOption
wantBare bool
wantBranch string
}{
{
name: "Bare",
opts: func() []InitOption { return nil },
wantBare: true,
},
{
name: "With Worktree",
opts: func() []InitOption {
return []InitOption{WithWorkTree(memfs.New())}
},
},
{
name: "With Default Branch",
opts: func() []InitOption {
return []InitOption{
WithWorkTree(memfs.New()),
WithDefaultBranch("refs/head/foo"),
}
},
wantBranch: "refs/head/foo",
},
}
forEachFormat(t, func(t *testing.T, of formatcfg.ObjectFormat) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
opts := append(tc.opts(), WithObjectFormat(of))
rdir := t.TempDir()
r, err := PlainInit(rdir, tc.wantBare, opts...)
require.NotNil(t, r)
require.NoError(t, err)
defer func() { _ = r.Close() }()
cfg, err := r.Config()
require.NoError(t, err)
assert.Equal(t, tc.wantBare, cfg.Core.IsBare)
if !tc.wantBare {
h := createCommit(t, r)
assert.Equal(t, of.HexSize(), len(h.String()))
wantBranch := tc.wantBranch
if wantBranch == "" {
wantBranch = plumbing.Master.String()
}
ref, err := r.Head()
require.NoError(t, err)
require.Equal(t, wantBranch, ref.Name().String())
}
ro, err := PlainOpen(rdir)
require.NotNil(t, ro)
require.NoError(t, err)
defer func() { _ = ro.Close() }()
if !tc.wantBare {
ref, err := ro.Head()
require.NoError(t, err)
assert.Equal(t, of.HexSize(), len(ref.Hash().String()))
}
})
}
})
}
type RepositorySuite struct {
BaseSuite
}
func TestRepositorySuite(t *testing.T) {
t.Parallel()
suite.Run(t, new(RepositorySuite))
}
func (s *RepositorySuite) TestInitWithInvalidDefaultBranch() {
r, err := Init(memory.NewStorage(), WithWorkTree(memfs.New()),
WithDefaultBranch("foo"),
)
if r != nil {
defer func() { _ = r.Close() }()
}
s.NotNil(err)
}
func (s *RepositorySuite) TestInitNonStandardDotGit() {
dir := s.T().TempDir()
fs := osfs.New(dir)
dot, _ := fs.Chroot("storage")
st := filesystem.NewStorage(dot, cache.NewObjectLRUDefault())
wt, _ := fs.Chroot("worktree")
r, err := Init(st, WithWorkTree(wt))
s.NoError(err)
s.NotNil(r)
defer func() { _ = r.Close() }()
f, err := fs.Open(fs.Join("worktree", ".git"))
s.NoError(err)
defer func() { _ = f.Close() }()
all, err := io.ReadAll(f)
s.NoError(err)
s.Equal(string(all), fmt.Sprintf("gitdir: %s\n", filepath.Join("..", "storage")))
cfg, err := r.Config()
s.NoError(err)
s.Equal(cfg.Core.Worktree, filepath.Join("..", "worktree"))
}
func (s *RepositorySuite) TestInitStandardDotGit() {
dir := s.T().TempDir()
fs := osfs.New(dir)
dot, _ := fs.Chroot(".git")
st := filesystem.NewStorage(dot, cache.NewObjectLRUDefault())
r, err := Init(st, WithWorkTree(fs))
s.NoError(err)
s.NotNil(r)
defer func() { _ = r.Close() }()
l, err := fs.ReadDir(".git")
s.NoError(err)
s.True(len(l) > 0)
cfg, err := r.Config()
s.NoError(err)
s.Equal("", cfg.Core.Worktree)
}
func (s *RepositorySuite) TestInitAlreadyExists() {
st := memory.NewStorage()
r, err := Init(st)
s.NoError(err)
s.NotNil(r)
_ = r.Close()
r, err = Init(st)
if r != nil {
defer func() { _ = r.Close() }()
}
s.ErrorIs(err, ErrTargetDirNotEmpty)
s.Nil(r)
}
func (s *RepositorySuite) TestOpen() {
st := memory.NewStorage()
r, err := Init(st, WithWorkTree(memfs.New()))
s.NoError(err)
s.NotNil(r)
_ = r.Close()
r, err = Open(st, memfs.New())
s.NoError(err)
s.NotNil(r)
_ = r.Close()
}
func (s *RepositorySuite) TestOpenBare() {
st := memory.NewStorage()
r, err := Init(st)
s.NoError(err)
s.NotNil(r)
_ = r.Close()
r, err = Open(st, nil)
s.NoError(err)
s.NotNil(r)
_ = r.Close()
}
func (s *RepositorySuite) TestOpenBareMissingWorktree() {
st := memory.NewStorage()
r, err := Init(st, WithWorkTree(memfs.New()))
s.NoError(err)
s.NotNil(r)
_ = r.Close()
r, err = Open(st, nil)
s.NoError(err)
s.NotNil(r)
_ = r.Close()
}
func (s *RepositorySuite) TestOpenNotExists() {
r, err := Open(memory.NewStorage(), nil)
s.ErrorIs(err, ErrRepositoryNotExists)
s.Nil(r)
}
func (s *RepositorySuite) TestClone() {
r, err := Clone(memory.NewStorage(), nil, &CloneOptions{
URL: s.GetBasicLocalRepositoryURL(),
})
s.NoError(err)
defer func() { _ = r.Close() }()
remotes, err := r.Remotes()
s.NoError(err)
s.Len(remotes, 1)
}
func TestCloneAll(t *testing.T) {
t.Parallel()
tests := []struct {
tag string
fixOF string
format formatcfg.ObjectFormat
refs int
plainClone bool
}{
{tag: ".git", fixOF: "sha256", format: formatcfg.SHA256, refs: 4},
{tag: ".git", fixOF: "sha1", format: formatcfg.UnsetObjectFormat, refs: 11},
{tag: ".git", fixOF: "sha256", format: formatcfg.SHA256, refs: 4, plainClone: true},
{tag: ".git", fixOF: "sha1", format: formatcfg.UnsetObjectFormat, refs: 11, plainClone: true},
}
for _, tc := range tests {
testName := fmt.Sprintf("%s/%s/plain=%t", tc.tag, tc.fixOF, tc.plainClone)
t.Run(testName, func(t *testing.T) {
t.Parallel()
f := fixtures.ByTag(tc.tag).ByObjectFormat(tc.fixOF).One()
for _, srv := range server.All(server.Loader(t, f)) {
endpoint, err := srv.Start()
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, srv.Close())
})
var r *Repository
if tc.plainClone {
r, err = PlainClone(t.TempDir(), &CloneOptions{URL: endpoint})
} else {
r, err = Clone(memory.NewStorage(), nil, &CloneOptions{
URL: endpoint,
})
}
require.NoError(t, err)
require.NotNil(t, r, "repository must not be nil")
defer func() { _ = r.Close() }()
remotes, err := r.Remotes()
require.NoError(t, err)
assert.Len(t, remotes, 1)
iter, err := r.References()
require.NoError(t, err)
refs := 0
iter.ForEach(func(_ *plumbing.Reference) error {
refs++
return nil
})
assert.Equal(t, tc.refs, refs)
cfg, err := r.Config()
require.NoError(t, err)
assert.Equal(t, tc.format, cfg.Extensions.ObjectFormat)
ref, err := r.Head()
require.NoError(t, err, "failed to get repository HEAD ref")
c, err := r.CommitObject(ref.Hash())
require.NoError(t, err, "failed to get commit object")
assert.NotNil(t, c)
}
})
}
}
func TestFetchMustNotUpdateObjectFormat(t *testing.T) {
t.Parallel()
tests := []struct {
name string
clientFormat formatcfg.ObjectFormat
serverTag string
fixOF string
wantErr bool
}{
{
name: "unset client format cannot fetch sha256",
clientFormat: formatcfg.UnsetObjectFormat,
serverTag: ".git",
fixOF: "sha256",
wantErr: true,
},
{
name: "sha1 client cannot fetch sha256",
clientFormat: formatcfg.SHA1,
serverTag: ".git",
fixOF: "sha256",
wantErr: true,
},
{
name: "sha256 client cannot fetch sha1",
clientFormat: formatcfg.SHA256,
serverTag: ".git",
fixOF: "sha1",
wantErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
f := fixtures.ByTag(tc.serverTag).ByObjectFormat(tc.fixOF).One()
require.NotNil(t, f, "fixture not found for tag %s", tc.serverTag)
for _, srv := range server.All(server.Loader(t, f)) {
endpoint, err := srv.Start()
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, srv.Close())
})
var st *memory.Storage
if tc.clientFormat == formatcfg.UnsetObjectFormat {
st = memory.NewStorage()
} else {
st = memory.NewStorage(memory.WithObjectFormat(tc.clientFormat))
}
r, err := Init(st)
require.NoError(t, err)
defer func() { _ = r.Close() }()
_, err = r.CreateRemote(&config.RemoteConfig{
Name: DefaultRemoteName,
URLs: []string{endpoint},
})
require.NoError(t, err)
err = r.Fetch(&FetchOptions{})
if tc.wantErr {
require.Error(t, err)
assert.Contains(t, err.Error(), "mismatched algorithms")
} else {
require.NoError(t, err)
}
}
})
}
}
// TestFetchByHashThenResolveRevision is a regression test for two bugs that
// affected fetching a specific commit by hash into an existing repository
// using the force-refspec "+<hash>:<hash>".
//
// Regression 1 (negotiate.go): shallow boundaries were not persisted after a
// clone, so subsequent fetches sent no "shallow" lines to the server. The
// server then inferred the client already owned the wanted commit (a deep
// ancestor of the shallow tip) and returned an empty packfile, leaving the
// object absent from the store.
//
// Regression 2 (remote.go): when the dst of a refspec is a bare SHA, the
// code created a branch named after the hash (refs/heads/<sha>) pointing to
// the zero hash. ResolveRevision resolved via that spurious ref and returned
// the zero hash instead of the real commit hash, breaking all downstream
// callers such as Worktree.Checkout.
//
// Note: this test uses the live GitHub URL rather than a local fixture server
// because the fixture HTTP server does not implement depth filtering in
// upload-pack. Without depth support the server sends all objects on a
// depth=1 clone, making commitSHA present from the start and preventing
// regression 1 from being reproduced.
func TestFetchByHashThenResolveRevision(t *testing.T) {
t.Parallel()
// git-fixtures/basic.git commit graph (abbreviated):
//
// * 6ecf0ef vendor stuff <- refs/heads/master (HEAD)
// | * e8d3ffa some code in branch <- refs/heads/branch
// |/
// * 918c48b some code
// ...several more commits...
// * 35e8510 binary file <- commitSHA (deep ancestor of both)
// * b029517 Initial commit
//
// A depth=1 shallow clone of master fetches only 6ecf0ef2. The target
// commit (35e85108) is a deep historical ancestor, absent because it is
// pruned by the shallow depth limit — not because it is on a different branch.
const (
repoURL = "https://github.com/git-fixtures/basic.git"
commitSHA = "35e85108805c84807bc66a02d91535e1e24b38b9"
)
tmp := t.TempDir()
// Step 1: clone the default branch at depth=1.
// commitSHA is a deep ancestor excluded by the shallow depth limit.
r, err := PlainClone(tmp, &CloneOptions{
URL: repoURL,
Depth: 1,
Tags: NoTags,
})
require.NoError(t, err, "clone should succeed")
defer func() { _ = r.Close() }()
// Confirm the target commit is not yet available.
_, err = r.CommitObject(plumbing.NewHash(commitSHA))
require.Error(t, err, "commit should NOT be present in a shallow clone of master")
// Step 2: fetch the specific commit by hash using "+<hash>:<hash>".
// This is the standard refspec for fetching an arbitrary commit that is not
// the tip of a branch or tag.
refSpec := config.RefSpec("+" + commitSHA + ":" + commitSHA)
err = r.Fetch(&FetchOptions{
Depth: 1,
Force: true,
RefSpecs: []config.RefSpec{refSpec},
Tags: NoTags,
})
require.NoError(t, err, "fetch should succeed")
// Step 3: the commit object MUST now be present in the object store.
_, err = r.CommitObject(plumbing.NewHash(commitSHA))
assert.NoError(t, err,
"commit object must be present in the object store after a successful Fetch with '+<hash>:<hash>'",
)
// Step 4: regression 2 — no spurious refs/heads/<sha> must be created.
// Before the fix, updateLocalReferenceStorage created refs/heads/<sha>
// pointing to the zero hash for any bare-hash dst refspec.
_, refErr := r.Storer.Reference(plumbing.NewBranchReferenceName(commitSHA))
assert.Error(t, refErr,
"fetching by hash must NOT create a branch named after the hash")
// Step 5: the commit must also be resolvable as a revision.
// Before the fix, the spurious branch caused ResolveRevision to return
// the zero hash.
hash, err := r.ResolveRevision(plumbing.Revision(commitSHA))
assert.NoError(t, err,
"ResolveRevision with a full SHA must succeed when the commit object is present",
)
if hash != nil {
assert.Equal(t, commitSHA, hash.String())
}
// Step 6: downstream effect — Worktree.Checkout must also succeed.
w, err := r.Worktree()
require.NoError(t, err)
err = w.Checkout(&CheckoutOptions{
Hash: plumbing.NewHash(commitSHA),
Force: true,
})
assert.NoError(t, err, "Worktree.Checkout by hash should succeed after fetching the commit")
}
// TestPlainCloneContext_FailedCloneRemovesCreatedDirectory is a regression test
// for a v6 behaviour difference vs v5 and the reference git implementation.
//
// When PlainCloneContext creates the destination directory (i.e. it did not
// exist before the call) and the clone subsequently fails, it must remove the
// directory it created — just as `git clone` does. Without this cleanup a
// caller that retries with different credentials (e.g. iterating over auth
// methods) gets "destination path already exists" on the second attempt.
func TestPlainCloneContext_FailedCloneRemovesCreatedDirectory(t *testing.T) {
t.Parallel()
// dest does not exist yet; PlainCloneContext must create and then remove it.
dest := filepath.Join(t.TempDir(), "repo")
_, err := PlainCloneContext(context.Background(), dest, &CloneOptions{
URL: "incorrectOnPurpose",
})
require.Error(t, err)
_, statErr := os.Stat(dest)
assert.True(t, os.IsNotExist(statErr),
"PlainCloneContext must remove the directory it created when the clone fails")
}
// TestPlainCloneContext_FailedClonePreservesPreexistingEmptyDirectory verifies
// that a directory which already existed (but was empty) before the call is
// preserved after a failed clone — matching `git clone` behaviour.
func TestPlainCloneContext_FailedClonePreservesPreexistingEmptyDirectory(t *testing.T) {
t.Parallel()
// dest exists and is empty before the clone attempt.
dest := t.TempDir()
_, err := PlainCloneContext(context.Background(), dest, &CloneOptions{
URL: "incorrectOnPurpose",
})
require.Error(t, err)
// The directory itself must still be there …
_, statErr := os.Stat(dest)
assert.NoError(t, statErr, "PlainCloneContext must not remove a pre-existing directory")
// … and must be empty (any .git content added by PlainInit must be removed).
entries, _ := os.ReadDir(dest)
assert.Empty(t, entries,
"PlainCloneContext must remove any content it added to a pre-existing empty directory")
}
// TestPlainCloneContext_EmptyRemoteReturnsError verifies that cloning an
// empty remote repository returns ErrEmptyRemoteRepository by default.
func TestPlainCloneContext_EmptyRemoteReturnsError(t *testing.T) {
t.Parallel()
remote := filepath.Join(t.TempDir(), "remote.git")
remoteRepo, err := PlainInit(remote, true)
require.NoError(t, err)
_ = remoteRepo.Close()
dest := filepath.Join(t.TempDir(), "clone")
_, err = PlainCloneContext(context.Background(), dest, &CloneOptions{
URL: remote,
})
require.ErrorIs(t, err, transport.ErrEmptyRemoteRepository)
}
// TestPlainCloneContext_EmptyRemoteDoesNotCleanup verifies that cloning an
// empty remote repository with AllowEmptyRepo does not remove the directory.
func TestPlainCloneContext_EmptyRemoteDoesNotCleanup(t *testing.T) {
t.Parallel()
// Create a bare empty repository to use as the remote.
remote := filepath.Join(t.TempDir(), "remote.git")
remoteRepo, err := PlainInit(remote, true)
require.NoError(t, err)
defer func() { _ = remoteRepo.Close() }()
dest := filepath.Join(t.TempDir(), "clone")
r, err := PlainCloneContext(context.Background(), dest, &CloneOptions{
URL: remote,
AllowEmptyRepo: true,
})
require.NoError(t, err)
require.NotNil(t, r)
defer func() { _ = r.Close() }()
// The cloned repo should have the "origin" remote configured.
remotes, err := r.Remotes()
require.NoError(t, err)
require.Len(t, remotes, 1)
assert.Equal(t, "origin", remotes[0].Config().Name)
// The .git directory must still exist — the repo was initialized successfully.
_, statErr := os.Stat(filepath.Join(dest, GitDirName))
assert.NoError(t, statErr,
"PlainCloneContext must not remove .git when cloning an empty remote")
// HEAD must be a valid symbolic reference (not .invalid), because
// AllowEmptyRepo skips withPartialInit and fully initialises the repo.
head, err := r.Reference(plumbing.HEAD, false)
require.NoError(t, err)
assert.Equal(t, plumbing.SymbolicReference, head.Type())
assert.NotEqual(t, plumbing.Invalid, head.Target(),
"HEAD must not point to .invalid when AllowEmptyRepo is set")
// The repository should be re-openable — a fully initialised repo has
// its config persisted (unlike a partialInit repo).
reopened, err := PlainOpen(dest)
require.NoError(t, err)
defer func() { _ = reopened.Close() }()
reopenedRemotes, err := reopened.Remotes()
require.NoError(t, err)
require.Len(t, reopenedRemotes, 1)
assert.Equal(t, "origin", reopenedRemotes[0].Config().Name)
}
// TestPlainCloneContext_DetachedHeadSource is a regression test for a bug
// where PlainCloneContext returns plumbing.ErrReferenceNotFound when the
// source repository has a detached HEAD.
//
// A detached HEAD is the normal state of a repository after
// Worktree.Checkout is called with CheckoutOptions{Hash: someHash}.
// Cloning FROM such a repo (e.g. when using a local filesystem directory
// as a "remote") must succeed, just as `git clone` does.
func TestPlainCloneContext_DetachedHeadSource(t *testing.T) {
t.Parallel()
// ── Build the source repo using PlainInit + Worktree.Commit ──────────
// Self-contained: no network access required.
srcDir := t.TempDir()
src, err := PlainInit(srcDir, false)
require.NoError(t, err)
defer func() { _ = src.Close() }()
wt, err := src.Worktree()
require.NoError(t, err)
// Write a file and create an initial commit so HEAD resolves to a real hash.
err = os.WriteFile(filepath.Join(srcDir, "README.md"), []byte("hello"), 0o644)
require.NoError(t, err)
_, err = wt.Add("README.md")
require.NoError(t, err)
commitHash, err := wt.Commit("initial commit", &CommitOptions{
Author: &object.Signature{Name: "Test", Email: "t@t.com"},
})
require.NoError(t, err)
// Verify HEAD is a symbolic reference before detaching.
rawHead, err := src.Storer.Reference(plumbing.HEAD)
require.NoError(t, err)
require.Equal(t, plumbing.SymbolicReference, rawHead.Type(),
"HEAD should be a symbolic ref after commit")
// Detach HEAD by checking out by hash.
err = wt.Checkout(&CheckoutOptions{Hash: commitHash, Force: true})
require.NoError(t, err)
detachedHead, err := src.Storer.Reference(plumbing.HEAD)
require.NoError(t, err)
require.Equal(t, plumbing.HashReference, detachedHead.Type(),
"HEAD must be a hash-reference (detached) after Checkout{Hash:...}")
// ── Clone from the detached-HEAD source ───────────────────────────────
// The branch ref (refs/heads/master) still exists in the source object
// store; only HEAD is detached. PlainCloneContext must succeed — just as
// `git clone` does — by advertising the available refs rather than
// requiring HEAD to be symbolic.
dstDir := filepath.Join(t.TempDir(), "dst")
dst, err := PlainCloneContext(context.Background(), dstDir, &CloneOptions{
URL: srcDir,
})
assert.NoError(t, err,
"PlainCloneContext must succeed when the source repo has a detached HEAD")
// ── Verify the cloned repo behaves like `git clone` ──────────────────────
// git clone creates a symbolic HEAD (→ refs/heads/<branch>) in the clone
// even when the source has a detached HEAD; the resolved commit must match.
require.NotNil(t, dst, "cloned repository must not be nil")
defer func() { _ = dst.Close() }()
rawClonedHead, err := dst.Storer.Reference(plumbing.HEAD)
require.NoError(t, err)
assert.Equal(t, plumbing.SymbolicReference, rawClonedHead.Type(),
"cloned repo HEAD must be a symbolic ref (as git clone produces), not detached")
resolvedHead, err := dst.Head()
require.NoError(t, err)
assert.Equal(t, commitHash, resolvedHead.Hash(),
"cloned repo HEAD must resolve to the same commit as the source")
}
// sha1OnlyStorage wraps a storage.Storer to hide the ExtensionChecker
// implementation, simulating a storage backend that does not implement
// that interface.
type sha1OnlyStorage struct {
storage.Storer
}
func TestFailSafeUnsupportedStorage(t *testing.T) {
t.Parallel()
t.Run("clone", func(t *testing.T) {
t.Parallel()
f := fixtures.ByTag(".git").ByObjectFormat("sha256").One()
require.NotNil(t, f, "fixture not found")
for _, srv := range server.All(server.Loader(t, f)) {
endpoint, err := srv.Start()
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, srv.Close())
})
st := &sha1OnlyStorage{memory.NewStorage()}
_, okGetter := storage.Storer(st).(xstorage.ExtensionChecker)
assert.False(t, okGetter, "sha1OnlyStorage must not implement ExtensionChecker")
r, err := Clone(st, nil, &CloneOptions{URL: endpoint})
if r != nil {
defer func() { _ = r.Close() }()
}
require.Error(t, err)
assert.Contains(t, err.Error(), "mismatched algorithms")
}
})
t.Run("open", func(t *testing.T) {
t.Parallel()
f := fixtures.ByTag(".git").ByObjectFormat("sha256").One()
require.NotNil(t, f, "fixture not found")
dotgit, dotgitErr := f.DotGit(fixtures.WithMemFS())
require.NoError(t, dotgitErr)
st := filesystem.NewStorage(dotgit, cache.NewObjectLRUDefault())
defer func() { _ = st.Close() }()
wrapped := &sha1OnlyStorage{st}
_, okGetter := storage.Storer(wrapped).(xstorage.ExtensionChecker)
assert.False(t, okGetter, "sha1OnlyStorage must not implement ExtensionChecker")
r, err := Open(wrapped, nil)
assert.Error(t, err)
assert.Nil(t, r)
})
}
func (s *RepositorySuite) TestCloneContext() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
r, err := CloneContext(ctx, memory.NewStorage(), nil, &CloneOptions{
URL: s.GetBasicLocalRepositoryURL(),
})
s.NotNil(r)
_ = r.Close()
s.ErrorIs(err, context.Canceled)
}
func (s *RepositorySuite) TestCloneMirror() {
r, err := Clone(memory.NewStorage(), nil, &CloneOptions{
URL: fixtures.Basic().One().URL,
Mirror: true,
})
s.NoError(err)
defer func() { _ = r.Close() }()
refs, err := r.References()
var count int
refs.ForEach(func(r *plumbing.Reference) error { s.T().Log(r); count++; return nil })
s.NoError(err)
// 6 refs total from github.com/git-fixtures/basic.git:
// - HEAD
// - refs/heads/master
// - refs/heads/branch
// - refs/pull/1/head
// - refs/pull/2/head
// - refs/pull/2/merge
s.Equal(6, count)
cfg, err := r.Config()
s.NoError(err)
s.True(cfg.Core.IsBare)
s.Nil(cfg.Remotes[DefaultRemoteName].Validate())
s.True(cfg.Remotes[DefaultRemoteName].Mirror)
}
func (s *RepositorySuite) TestCloneWithTags() {
url := s.GetLocalRepositoryURL(
fixtures.ByURL("https://github.com/git-fixtures/tags.git").One(),
)
r, err := Clone(memory.NewStorage(), nil, &CloneOptions{URL: url, Tags: NoTags})
s.NoError(err)
defer func() { _ = r.Close() }()
remotes, err := r.Remotes()
s.NoError(err)
s.Len(remotes, 1)
i, err := r.References()
s.NoError(err)
var count int
i.ForEach(func(*plumbing.Reference) error { count++; return nil })
s.Equal(3, count)
}
func (s *RepositorySuite) TestCloneSparse() {
fs := memfs.New()
r, err := Clone(memory.NewStorage(), fs, &CloneOptions{
URL: s.GetBasicLocalRepositoryURL(),
NoCheckout: true,
})
s.NoError(err)
defer func() { _ = r.Close() }()
w, err := r.Worktree()
s.NoError(err)
sparseCheckoutDirectories := []string{"go", "json", "php"}
s.NoError(w.Checkout(&CheckoutOptions{
Branch: "refs/heads/master",
SparseCheckoutDirectories: sparseCheckoutDirectories,
}))
fis, err := fs.ReadDir(".")
s.NoError(err)
for _, fi := range fis {
s.True(fi.IsDir())
var oneOfSparseCheckoutDirs bool
for _, sparseCheckoutDirectory := range sparseCheckoutDirectories {
if strings.HasPrefix(fi.Name(), sparseCheckoutDirectory) {
oneOfSparseCheckoutDirs = true
}
}
s.True(oneOfSparseCheckoutDirs)
}
}
func (s *RepositorySuite) TestCreateRemoteAndRemote() {
r, _ := Init(memory.NewStorage())
defer func() { _ = r.Close() }()
remote, err := r.CreateRemote(&config.RemoteConfig{
Name: "foo",
URLs: []string{"http://foo/foo.git"},
})
s.NoError(err)
s.Equal("foo", remote.Config().Name)
alt, err := r.Remote("foo")
s.NoError(err)
s.NotSame(remote, alt)
s.Equal("foo", alt.Config().Name)
}
func (s *RepositorySuite) TestCreateRemoteInvalid() {
r, _ := Init(memory.NewStorage())
defer func() { _ = r.Close() }()
remote, err := r.CreateRemote(&config.RemoteConfig{})
s.ErrorIs(err, config.ErrRemoteConfigEmptyName)
s.Nil(remote)
}
func (s *RepositorySuite) TestCreateRemoteAnonymous() {
r, _ := Init(memory.NewStorage())
defer func() { _ = r.Close() }()
remote, err := r.CreateRemoteAnonymous(&config.RemoteConfig{
Name: "anonymous",
URLs: []string{"http://foo/foo.git"},
})
s.NoError(err)
s.Equal("anonymous", remote.Config().Name)
}
func (s *RepositorySuite) TestCreateRemoteAnonymousInvalidName() {
r, _ := Init(memory.NewStorage())
defer func() { _ = r.Close() }()
remote, err := r.CreateRemoteAnonymous(&config.RemoteConfig{
Name: "not_anonymous",
URLs: []string{"http://foo/foo.git"},
})
s.ErrorIs(err, ErrAnonymousRemoteName)
s.Nil(remote)
}
func (s *RepositorySuite) TestCreateRemoteAnonymousInvalid() {
r, _ := Init(memory.NewStorage())
defer func() { _ = r.Close() }()
remote, err := r.CreateRemoteAnonymous(&config.RemoteConfig{})
s.ErrorIs(err, config.ErrRemoteConfigEmptyName)
s.Nil(remote)
}
func (s *RepositorySuite) TestDeleteRemote() {
r, _ := Init(memory.NewStorage())
defer func() { _ = r.Close() }()
_, err := r.CreateRemote(&config.RemoteConfig{
Name: "foo",
URLs: []string{"http://foo/foo.git"},
})
s.NoError(err)
You can’t perform that action at this time.
