Debian Codegraph @

storage/filesystem/dotgit/dotgit_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package dotgit
2
3 import (
4 "bufio"
5 "encoding/hex"
6 "errors"
7 "io"
8 "os"
9 "path/filepath"
10 "regexp"
11 "runtime"
12 "strings"
13 "testing"
14
15 "github.com/go-git/go-billy/v5"
16 "github.com/go-git/go-billy/v5/memfs"
17 "github.com/go-git/go-billy/v5/osfs"
18 "github.com/go-git/go-billy/v5/util"
19 fixtures "github.com/go-git/go-git-fixtures/v4"
20 "github.com/go-git/go-git/v5/plumbing"
21 "github.com/go-git/go-git/v5/storage"
22 "github.com/stretchr/testify/assert"
23 "github.com/stretchr/testify/require"
24 . "gopkg.in/check.v1"
25 )
26
27 func Test(t *testing.T) { TestingT(t) }
28
29 type SuiteDotGit struct {
30 fixtures.Suite
31 }
32
33 var _ = Suite(&SuiteDotGit{})
34
35 func (s *SuiteDotGit) TemporalFilesystem(c *C) (fs billy.Filesystem) {
36 fs = osfs.New(c.MkDir())
37 path, err := util.TempDir(fs, "", "")
38 if err != nil {
39 panic(err)
40 }
41
42 fs, err = fs.Chroot(path)
43 if err != nil {
44 panic(err)
45 }
46
47 return fs
48 }
49
50 func (s *SuiteDotGit) TestModuleRejectsEscapingNames(c *C) {
51 d := New(memfs.New())
52 // Only true path-traversal cases — names like "/etc" or
53 // "modules/../escape" land inside modules/ once Join cleans
54 // them, so the containment check correctly accepts those.
55 bad := []string{
56 "..",
57 "../x",
58 "foo/../..",
59 "a/b/c/../../../..",
60 }
61 for _, n := range bad {
62 _, err := d.Module(n)
63 c.Assert(errors.Is(err, ErrModuleNameEscape), Equals, true,
64 Commentf("name %q", n))
65 }
66 }
67
68 func (s *SuiteDotGit) TestModuleAcceptsBenignNames(c *C) {
69 d := New(memfs.New())
70 for _, n := range []string{"foo", "lib/foo", "x.y"} {
71 _, err := d.Module(n)
72 c.Assert(err, IsNil, Commentf("name %q", n))
73 }
74 }
75
76 func (s *SuiteDotGit) TestReferenceNameRejectsEscapingNames(c *C) {
77 d := New(memfs.New())
78 c.Assert(d.Initialize(), IsNil)
79
80 // A ".." component (or a control character) lets a reference name climb
81 // out of its sub-tree into unrelated .git metadata such as config; a
82 // malicious remote can advertise such a name and, after refspec mapping,
83 // have it reach the storage layer.
84 bad := []plumbing.ReferenceName{
85 "refs/heads/../../config",
86 "refs/remotes/origin/../../../config",
87 "refs/heads/..",
88 "refs/heads/foo\x00bar",
89 }
90 for _, n := range bad {
91 ref := plumbing.NewHashReference(n, plumbing.NewHash("e8d3ffab552895c19b9fcf7aa264d277cde33881"))
92 c.Assert(errors.Is(d.SetRef(ref, nil), ErrReferenceNameEscape), Equals, true, Commentf("SetRef %q", n))
93
94 _, err := d.Ref(n)
95 c.Assert(errors.Is(err, ErrReferenceNameEscape), Equals, true, Commentf("Ref %q", n))
96
97 c.Assert(errors.Is(d.RemoveRef(n), ErrReferenceNameEscape), Equals, true, Commentf("RemoveRef %q", n))
98 }
99
100 // The rejected traversals must not have written .git/config.
101 _, err := d.fs.Stat(configPath)
102 c.Assert(err, NotNil, Commentf("traversal must not create .git/config"))
103 }
104
105 func (s *SuiteDotGit) TestReferenceNameRejectsWindowsDisguisedTraversal(c *C) {
106 d := New(memfs.New())
107 c.Assert(d.Initialize(), IsNil)
108
109 // On NTFS, ".." followed by trailing periods/spaces or an Alternate Data
110 // Stream / $INDEX_ALLOCATION suffix is canonicalised back to "..", so a
111 // literal `== ".."` check would miss these while the filesystem still
112 // performs the parent-directory hop. These are pure-string checks, so the
113 // containment must hold on every host, not only Windows.
114 bad := []plumbing.ReferenceName{
115 "refs/heads/..::$INDEX_ALLOCATION",
116 "refs/heads/..:$DATA",
117 "refs/heads/.. /config",
118 "refs/heads/.../config",
119 }
120 for _, n := range bad {
121 ref := plumbing.NewHashReference(n, plumbing.NewHash("e8d3ffab552895c19b9fcf7aa264d277cde33881"))
122 c.Assert(errors.Is(d.SetRef(ref, nil), ErrReferenceNameEscape), Equals, true, Commentf("SetRef %q", n))
123
124 _, err := d.Ref(n)
125 c.Assert(errors.Is(err, ErrReferenceNameEscape), Equals, true, Commentf("Ref %q", n))
126 }
127
128 _, err := d.fs.Stat(configPath)
129 c.Assert(err, NotNil, Commentf("traversal must not create .git/config"))
130 }
131
132 func (s *SuiteDotGit) TestReferenceNameRejectsHFSDisguisedTraversal(c *C) {
133 d := New(memfs.New())
134 c.Assert(d.Initialize(), IsNil)
135
136 // HFS+ strips a set of ignorable Unicode code points during
137 // normalisation, so ".<U+200C>." (zero-width non-joiner) collapses to
138 // ".." on disk. As above, this is a string-level check that must hold
139 // regardless of host OS.
140 n := plumbing.ReferenceName("refs/heads/." + "\u200c" + "./config")
141 ref := plumbing.NewHashReference(n, plumbing.NewHash("e8d3ffab552895c19b9fcf7aa264d277cde33881"))
142 c.Assert(errors.Is(d.SetRef(ref, nil), ErrReferenceNameEscape), Equals, true, Commentf("SetRef %q", n))
143
144 _, err := d.Ref(n)
145 c.Assert(errors.Is(err, ErrReferenceNameEscape), Equals, true, Commentf("Ref %q", n))
146
147 _, err = d.fs.Stat(configPath)
148 c.Assert(err, NotNil, Commentf("traversal must not create .git/config"))
149 }
150
151 func (s *SuiteDotGit) TestReferenceNameRejectsAbsoluteAndDriveNames(c *C) {
152 d := New(memfs.New())
153 c.Assert(d.Initialize(), IsNil)
154
155 // A leading or trailing separator, or a drive-letter prefix, lets the
156 // name collapse onto a top-level .git file (e.g. "/config" -> .git/config)
157 // once joined. filepath.VolumeName alone would not catch "C:config" off
158 // Windows, so these are rejected host-independently as validSubmoduleName
159 // does.
160 bad := []plumbing.ReferenceName{
161 "/config",
162 "\\config",
163 "C:config",
164 "refs/heads/foo/",
165 "",
166 }
167 for _, n := range bad {
168 ref := plumbing.NewHashReference(n, plumbing.NewHash("e8d3ffab552895c19b9fcf7aa264d277cde33881"))
169 c.Assert(errors.Is(d.SetRef(ref, nil), ErrReferenceNameEscape), Equals, true, Commentf("SetRef %q", n))
170
171 _, err := d.Ref(n)
172 c.Assert(errors.Is(err, ErrReferenceNameEscape), Equals, true, Commentf("Ref %q", n))
173 c.Assert(errors.Is(d.RemoveRef(n), ErrReferenceNameEscape), Equals, true, Commentf("RemoveRef %q", n))
174 }
175
176 _, err := d.fs.Stat(configPath)
177 c.Assert(err, NotNil, Commentf("must not create .git/config"))
178 }
179
180 func (s *SuiteDotGit) TestReferenceNameRejectsTopLevelMetadata(c *C) {
181 d := New(memfs.New())
182 c.Assert(d.Initialize(), IsNil)
183
184 // A single-level name that is neither under refs/ nor a [A-Z_] pseudo-ref
185 // would land on top-level .git metadata once joined; the IsSafe gate
186 // rejects it, matching upstream refname_is_safe.
187 bad := []plumbing.ReferenceName{
188 "config", "config.worktree", "index", "packed-refs",
189 "shallow", "hooks", "objects", "bar", "HEAD2", "head",
190 }
191 for _, n := range bad {
192 ref := plumbing.NewHashReference(n, plumbing.NewHash("e8d3ffab552895c19b9fcf7aa264d277cde33881"))
193 c.Assert(errors.Is(d.SetRef(ref, nil), ErrReferenceNameEscape), Equals, true, Commentf("SetRef %q", n))
194 }
195
196 _, err := d.fs.Stat(configPath)
197 c.Assert(err, NotNil, Commentf("must not create .git/config"))
198 }
199
200 func (s *SuiteDotGit) TestReferenceNameAcceptsBenignNames(c *C) {
201 d := New(memfs.New())
202 c.Assert(d.Initialize(), IsNil)
203 for _, n := range []plumbing.ReferenceName{
204 "HEAD", "ORIG_HEAD", "FETCH_HEAD", "MERGE_HEAD", "CHERRY_PICK_HEAD",
205 "refs/heads/main", "refs/heads/release-1.2",
206 "refs/tags/v1.0.0", "refs/remotes/origin/HEAD", "refs/stash",
207 } {
208 ref := plumbing.NewHashReference(n, plumbing.NewHash("e8d3ffab552895c19b9fcf7aa264d277cde33881"))
209 c.Assert(d.SetRef(ref, nil), IsNil, Commentf("SetRef %q", n))
210 }
211 }
212
213 func (s *SuiteDotGit) TestInitialize(c *C) {
214 fs := s.TemporalFilesystem(c)
215
216 dir := New(fs)
217
218 err := dir.Initialize()
219 c.Assert(err, IsNil)
220
221 _, err = fs.Stat(fs.Join("objects", "info"))
222 c.Assert(err, IsNil)
223
224 _, err = fs.Stat(fs.Join("objects", "pack"))
225 c.Assert(err, IsNil)
226
227 _, err = fs.Stat(fs.Join("refs", "heads"))
228 c.Assert(err, IsNil)
229
230 _, err = fs.Stat(fs.Join("refs", "tags"))
231 c.Assert(err, IsNil)
232 }
233
234 func (s *SuiteDotGit) TestSetRefs(c *C) {
235 fs := s.TemporalFilesystem(c)
236
237 dir := New(fs)
238
239 testSetRefs(c, dir)
240 }
241
242 func (s *SuiteDotGit) TestSetRefsNorwfs(c *C) {
243 fs := s.TemporalFilesystem(c)
244
245 dir := New(&norwfs{fs})
246
247 testSetRefs(c, dir)
248 }
249
250 func (s *SuiteDotGit) TestRefsHeadFirst(c *C) {
251 fs := fixtures.Basic().ByTag(".git").One().DotGit()
252 dir := New(fs)
253 refs, err := dir.Refs()
254 c.Assert(err, IsNil)
255 c.Assert(len(refs), Not(Equals), 0)
256 c.Assert(refs[0].Name().String(), Equals, "HEAD")
257 }
258
259 func testSetRefs(c *C, dir *DotGit) {
260 firstFoo := plumbing.NewReferenceFromStrings(
261 "refs/heads/foo",
262 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
263 )
264 err := dir.SetRef(firstFoo, nil)
265
266 c.Assert(err, IsNil)
267
268 err = dir.SetRef(plumbing.NewReferenceFromStrings(
269 "refs/heads/symbolic",
270 "ref: refs/heads/foo",
271 ), nil)
272
273 c.Assert(err, IsNil)
274
275 // A single-level, non-pseudo-ref name is refused: it is not under refs/
276 // and its spelling is not the [A-Z_] pseudo-ref form (upstream
277 // refname_is_safe rejects it likewise).
278 err = dir.SetRef(plumbing.NewReferenceFromStrings(
279 "bar",
280 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
281 ), nil)
282 c.Assert(errors.Is(err, ErrReferenceNameEscape), Equals, true)
283
284 err = dir.SetRef(plumbing.NewReferenceFromStrings(
285 "refs/heads/feature/baz",
286 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
287 ), nil)
288 c.Assert(err, IsNil)
289
290 refs, err := dir.Refs()
291 c.Assert(err, IsNil)
292 c.Assert(refs, HasLen, 3)
293
294 ref := findReference(refs, "refs/heads/foo")
295 c.Assert(ref, NotNil)
296 c.Assert(ref.Hash().String(), Equals, "e8d3ffab552895c19b9fcf7aa264d277cde33881")
297
298 ref = findReference(refs, "refs/heads/symbolic")
299 c.Assert(ref, NotNil)
300 c.Assert(ref.Target().String(), Equals, "refs/heads/foo")
301
302 ref = findReference(refs, "bar")
303 c.Assert(ref, IsNil)
304
305 _, err = dir.readReferenceFile(".", "refs/heads/feature/baz")
306 c.Assert(err, IsNil)
307
308 _, err = dir.readReferenceFile(".", "refs/heads/feature")
309 c.Assert(err, Equals, ErrIsDir)
310
311 ref, err = dir.Ref("refs/heads/foo")
312 c.Assert(err, IsNil)
313 c.Assert(ref, NotNil)
314 c.Assert(ref.Hash().String(), Equals, "e8d3ffab552895c19b9fcf7aa264d277cde33881")
315
316 ref, err = dir.Ref("refs/heads/symbolic")
317 c.Assert(err, IsNil)
318 c.Assert(ref, NotNil)
319 c.Assert(ref.Target().String(), Equals, "refs/heads/foo")
320
321 // "bar" was refused at write time and is refused at read time too.
322 _, err = dir.Ref("bar")
323 c.Assert(errors.Is(err, ErrReferenceNameEscape), Equals, true)
324
325 // Check that SetRef with a non-nil `old` works.
326 err = dir.SetRef(plumbing.NewReferenceFromStrings(
327 "refs/heads/foo",
328 "6ecf0ef2c2dffb796033e5a02219af86ec6584e5",
329 ), firstFoo)
330 c.Assert(err, IsNil)
331
332 // `firstFoo` is no longer the right `old` reference, so this
333 // should fail.
334 err = dir.SetRef(plumbing.NewReferenceFromStrings(
335 "refs/heads/foo",
336 "6ecf0ef2c2dffb796033e5a02219af86ec6584e5",
337 ), firstFoo)
338 c.Assert(err, NotNil)
339 }
340
341 func (s *SuiteDotGit) TestRefsFromPackedRefs(c *C) {
342 fs := fixtures.Basic().ByTag(".git").One().DotGit()
343 dir := New(fs)
344
345 refs, err := dir.Refs()
346 c.Assert(err, IsNil)
347
348 ref := findReference(refs, "refs/remotes/origin/branch")
349 c.Assert(ref, NotNil)
350 c.Assert(ref.Hash().String(), Equals, "e8d3ffab552895c19b9fcf7aa264d277cde33881")
351 }
352
353 func (s *SuiteDotGit) TestRefsFromReferenceFile(c *C) {
354 fs := fixtures.Basic().ByTag(".git").One().DotGit()
355 dir := New(fs)
356
357 refs, err := dir.Refs()
358 c.Assert(err, IsNil)
359
360 ref := findReference(refs, "refs/remotes/origin/HEAD")
361 c.Assert(ref, NotNil)
362 c.Assert(ref.Type(), Equals, plumbing.SymbolicReference)
363 c.Assert(string(ref.Target()), Equals, "refs/remotes/origin/master")
364 }
365
366 func BenchmarkRefMultipleTimes(b *testing.B) {
367 fs := fixtures.Basic().ByTag(".git").One().DotGit()
368 refname := plumbing.ReferenceName("refs/remotes/origin/branch")
369
370 dir := New(fs)
371 _, err := dir.Ref(refname)
372 if err != nil {
373 b.Fatalf("unexpected error: %s", err)
374 }
375
376 for i := 0; i < b.N; i++ {
377 _, err := dir.Ref(refname)
378 if err != nil {
379 b.Fatalf("unexpected error: %s", err)
380 }
381 }
382 }
383
384 func (s *SuiteDotGit) TestRemoveRefFromReferenceFile(c *C) {
385 fs := fixtures.Basic().ByTag(".git").One().DotGit()
386 dir := New(fs)
387
388 name := plumbing.ReferenceName("refs/remotes/origin/HEAD")
389 err := dir.RemoveRef(name)
390 c.Assert(err, IsNil)
391
392 refs, err := dir.Refs()
393 c.Assert(err, IsNil)
394
395 ref := findReference(refs, string(name))
396 c.Assert(ref, IsNil)
397 }
398
399 func (s *SuiteDotGit) TestRemoveRefFromPackedRefs(c *C) {
400 fs := fixtures.Basic().ByTag(".git").One().DotGit()
401 dir := New(fs)
402
403 name := plumbing.ReferenceName("refs/remotes/origin/master")
404 err := dir.RemoveRef(name)
405 c.Assert(err, IsNil)
406
407 b, err := util.ReadFile(fs, packedRefsPath)
408 c.Assert(err, IsNil)
409
410 c.Assert(string(b), Equals, ""+
411 "# pack-refs with: peeled fully-peeled \n"+
412 "6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/heads/master\n"+
413 "e8d3ffab552895c19b9fcf7aa264d277cde33881 refs/remotes/origin/branch\n")
414 }
415
416 func (s *SuiteDotGit) TestRemoveRefFromReferenceFileAndPackedRefs(c *C) {
417 fs := fixtures.Basic().ByTag(".git").One().DotGit()
418 dir := New(fs)
419
420 // Make a ref file for a ref that's already in `packed-refs`.
421 err := dir.SetRef(plumbing.NewReferenceFromStrings(
422 "refs/remotes/origin/branch",
423 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
424 ), nil)
425 c.Assert(err, IsNil)
426
427 // Make sure it only appears once in the refs list.
428 refs, err := dir.Refs()
429 c.Assert(err, IsNil)
430 found := false
431 for _, ref := range refs {
432 if ref.Name() == "refs/remotes/origin/branch" {
433 c.Assert(found, Equals, false)
434 found = true
435 }
436 }
437
438 name := plumbing.ReferenceName("refs/remotes/origin/branch")
439 err = dir.RemoveRef(name)
440 c.Assert(err, IsNil)
441
442 b, err := util.ReadFile(fs, packedRefsPath)
443 c.Assert(err, IsNil)
444
445 c.Assert(string(b), Equals, ""+
446 "# pack-refs with: peeled fully-peeled \n"+
447 "6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/heads/master\n"+
448 "6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/remotes/origin/master\n")
449
450 refs, err = dir.Refs()
451 c.Assert(err, IsNil)
452
453 ref := findReference(refs, string(name))
454 c.Assert(ref, IsNil)
455 }
456
457 func (s *SuiteDotGit) TestRemoveRefNonExistent(c *C) {
458 fs := fixtures.Basic().ByTag(".git").One().DotGit()
459 dir := New(fs)
460
461 before, err := util.ReadFile(fs, packedRefsPath)
462 c.Assert(err, IsNil)
463
464 name := plumbing.ReferenceName("refs/heads/nonexistent")
465 err = dir.RemoveRef(name)
466 c.Assert(err, IsNil)
467
468 after, err := util.ReadFile(fs, packedRefsPath)
469 c.Assert(err, IsNil)
470
471 c.Assert(string(before), Equals, string(after))
472 }
473
474 func (s *SuiteDotGit) TestRemoveRefInvalidPackedRefs(c *C) {
475 fs := fixtures.Basic().ByTag(".git").One().DotGit()
476 dir := New(fs)
477
478 brokenContent := "BROKEN STUFF REALLY BROKEN"
479
480 err := util.WriteFile(fs, packedRefsPath, []byte(brokenContent), os.FileMode(0755))
481 c.Assert(err, IsNil)
482
483 name := plumbing.ReferenceName("refs/heads/nonexistent")
484 err = dir.RemoveRef(name)
485 c.Assert(err, NotNil)
486
487 after, err := util.ReadFile(fs, packedRefsPath)
488 c.Assert(err, IsNil)
489
490 c.Assert(brokenContent, Equals, string(after))
491 }
492
493 func (s *SuiteDotGit) TestRemoveRefInvalidPackedRefs2(c *C) {
494 fs := fixtures.Basic().ByTag(".git").One().DotGit()
495 dir := New(fs)
496
497 brokenContent := strings.Repeat("a", bufio.MaxScanTokenSize*2)
498
499 err := util.WriteFile(fs, packedRefsPath, []byte(brokenContent), os.FileMode(0755))
500 c.Assert(err, IsNil)
501
502 name := plumbing.ReferenceName("refs/heads/nonexistent")
503 err = dir.RemoveRef(name)
504 c.Assert(err, NotNil)
505
506 after, err := util.ReadFile(fs, packedRefsPath)
507 c.Assert(err, IsNil)
508
509 c.Assert(brokenContent, Equals, string(after))
510 }
511
512 func (s *SuiteDotGit) TestRefsFromHEADFile(c *C) {
513 fs := fixtures.Basic().ByTag(".git").One().DotGit()
514 dir := New(fs)
515
516 refs, err := dir.Refs()
517 c.Assert(err, IsNil)
518
519 ref := findReference(refs, "HEAD")
520 c.Assert(ref, NotNil)
521 c.Assert(ref.Type(), Equals, plumbing.SymbolicReference)
522 c.Assert(string(ref.Target()), Equals, "refs/heads/master")
523 }
524
525 func (s *SuiteDotGit) TestConfig(c *C) {
526 fs := fixtures.Basic().ByTag(".git").One().DotGit()
527 dir := New(fs)
528
529 file, err := dir.Config()
530 c.Assert(err, IsNil)
531 c.Assert(filepath.Base(file.Name()), Equals, "config")
532 }
533
534 func (s *SuiteDotGit) TestConfigWriteAndConfig(c *C) {
535 fs := s.TemporalFilesystem(c)
536
537 dir := New(fs)
538
539 f, err := dir.ConfigWriter()
540 c.Assert(err, IsNil)
541
542 _, err = f.Write([]byte("foo"))
543 c.Assert(err, IsNil)
544
545 f, err = dir.Config()
546 c.Assert(err, IsNil)
547
548 cnt, err := io.ReadAll(f)
549 c.Assert(err, IsNil)
550
551 c.Assert(string(cnt), Equals, "foo")
552 }
553
554 func (s *SuiteDotGit) TestIndex(c *C) {
555 fs := fixtures.Basic().ByTag(".git").One().DotGit()
556 dir := New(fs)
557
558 idx, err := dir.Index()
559 c.Assert(err, IsNil)
560 c.Assert(idx, NotNil)
561 }
562
563 func (s *SuiteDotGit) TestIndexWriteAndIndex(c *C) {
564 fs := s.TemporalFilesystem(c)
565
566 dir := New(fs)
567
568 f, err := dir.IndexWriter()
569 c.Assert(err, IsNil)
570
571 _, err = f.Write([]byte("foo"))
572 c.Assert(err, IsNil)
573
574 f, err = dir.Index()
575 c.Assert(err, IsNil)
576
577 cnt, err := io.ReadAll(f)
578 c.Assert(err, IsNil)
579
580 c.Assert(string(cnt), Equals, "foo")
581 }
582
583 func (s *SuiteDotGit) TestShallow(c *C) {
584 fs := fixtures.Basic().ByTag(".git").One().DotGit()
585 dir := New(fs)
586
587 file, err := dir.Shallow()
588 c.Assert(err, IsNil)
589 c.Assert(file, IsNil)
590 }
591
592 func (s *SuiteDotGit) TestShallowWriteAndShallow(c *C) {
593 fs := s.TemporalFilesystem(c)
594
595 dir := New(fs)
596
597 f, err := dir.ShallowWriter()
598 c.Assert(err, IsNil)
599
600 _, err = f.Write([]byte("foo"))
601 c.Assert(err, IsNil)
602
603 f, err = dir.Shallow()
604 c.Assert(err, IsNil)
605
606 cnt, err := io.ReadAll(f)
607 c.Assert(err, IsNil)
608
609 c.Assert(string(cnt), Equals, "foo")
610 }
611
612 func findReference(refs []*plumbing.Reference, name string) *plumbing.Reference {
613 n := plumbing.ReferenceName(name)
614 for _, ref := range refs {
615 if ref.Name() == n {
616 return ref
617 }
618 }
619
620 return nil
621 }
622
623 func (s *SuiteDotGit) TestObjectPacks(c *C) {
624 f := fixtures.Basic().ByTag(".git").One()
625 fs := f.DotGit()
626 dir := New(fs)
627
628 testObjectPacks(c, fs, dir, f)
629 }
630
631 func (s *SuiteDotGit) TestObjectPacksExclusive(c *C) {
632 f := fixtures.Basic().ByTag(".git").One()
633 fs := f.DotGit()
634 dir := NewWithOptions(fs, Options{ExclusiveAccess: true})
635
636 testObjectPacks(c, fs, dir, f)
637 }
638
639 func testObjectPacks(c *C, fs billy.Filesystem, dir *DotGit, f *fixtures.Fixture) {
640 hashes, err := dir.ObjectPacks()
641 c.Assert(err, IsNil)
642 c.Assert(hashes, HasLen, 1)
643 c.Assert(hashes[0], Equals, plumbing.NewHash(f.PackfileHash))
644
645 // Make sure that a random file in the pack directory doesn't
646 // break everything.
647 badFile, err := fs.Create("objects/pack/OOPS_THIS_IS_NOT_RIGHT.pack")
648 c.Assert(err, IsNil)
649 err = badFile.Close()
650 c.Assert(err, IsNil)
651 // temporary file generated by git gc
652 tmpFile, err := fs.Create("objects/pack/.tmp-11111-pack-58rf8y4wm1b1k52bpe0kdlx6lpreg6ahso8n3ylc.pack")
653 c.Assert(err, IsNil)
654 err = tmpFile.Close()
655 c.Assert(err, IsNil)
656
657 hashes2, err := dir.ObjectPacks()
658 c.Assert(err, IsNil)
659 c.Assert(hashes2, HasLen, 1)
660 c.Assert(hashes[0], Equals, hashes2[0])
661 }
662
663 func (s *SuiteDotGit) TestObjectPack(c *C) {
664 f := fixtures.Basic().ByTag(".git").One()
665 fs := f.DotGit()
666 dir := New(fs)
667
668 pack, err := dir.ObjectPack(plumbing.NewHash(f.PackfileHash))
669 c.Assert(err, IsNil)
670 c.Assert(filepath.Ext(pack.Name()), Equals, ".pack")
671 }
672
673 func (s *SuiteDotGit) TestObjectPackWithKeepDescriptors(c *C) {
674 f := fixtures.Basic().ByTag(".git").One()
675 fs := f.DotGit()
676 dir := NewWithOptions(fs, Options{KeepDescriptors: true})
677
678 pack, err := dir.ObjectPack(plumbing.NewHash(f.PackfileHash))
679 c.Assert(err, IsNil)
680 c.Assert(filepath.Ext(pack.Name()), Equals, ".pack")
681
682 // Move to an specific offset
683 pack.Seek(42, io.SeekStart)
684
685 pack2, err := dir.ObjectPack(plumbing.NewHash(f.PackfileHash))
686 c.Assert(err, IsNil)
687
688 // If the file is the same the offset should be the same
689 offset, err := pack2.Seek(0, io.SeekCurrent)
690 c.Assert(err, IsNil)
691 c.Assert(offset, Equals, int64(42))
692
693 err = dir.Close()
694 c.Assert(err, IsNil)
695
696 pack2, err = dir.ObjectPack(plumbing.NewHash(f.PackfileHash))
697 c.Assert(err, IsNil)
698
699 // If the file is opened again its offset should be 0
700 offset, err = pack2.Seek(0, io.SeekCurrent)
701 c.Assert(err, IsNil)
702 c.Assert(offset, Equals, int64(0))
703
704 err = pack2.Close()
705 c.Assert(err, IsNil)
706
707 err = dir.Close()
708 c.Assert(err, NotNil)
709 }
710
711 func (s *SuiteDotGit) TestObjectPackIdx(c *C) {
712 f := fixtures.Basic().ByTag(".git").One()
713 fs := f.DotGit()
714 dir := New(fs)
715
716 idx, err := dir.ObjectPackIdx(plumbing.NewHash(f.PackfileHash))
717 c.Assert(err, IsNil)
718 c.Assert(filepath.Ext(idx.Name()), Equals, ".idx")
719 c.Assert(idx.Close(), IsNil)
720 }
721
722 func (s *SuiteDotGit) TestObjectPackNotFound(c *C) {
723 fs := fixtures.Basic().ByTag(".git").One().DotGit()
724 dir := New(fs)
725
726 pack, err := dir.ObjectPack(plumbing.ZeroHash)
727 c.Assert(err, Equals, ErrPackfileNotFound)
728 c.Assert(pack, IsNil)
729
730 idx, err := dir.ObjectPackIdx(plumbing.ZeroHash)
731 c.Assert(err, Equals, ErrPackfileNotFound)
732 c.Assert(idx, IsNil)
733 }
734
735 func (s *SuiteDotGit) TestNewObject(c *C) {
736 fs := s.TemporalFilesystem(c)
737
738 dir := New(fs)
739 w, err := dir.NewObject()
740 c.Assert(err, IsNil)
741
742 err = w.WriteHeader(plumbing.BlobObject, 14)
743 c.Assert(err, IsNil)
744 n, err := w.Write([]byte("this is a test"))
745 c.Assert(err, IsNil)
746 c.Assert(n, Equals, 14)
747
748 c.Assert(w.Hash().String(), Equals, "a8a940627d132695a9769df883f85992f0ff4a43")
749
750 err = w.Close()
751 c.Assert(err, IsNil)
752
753 i, err := fs.Stat("objects/a8/a940627d132695a9769df883f85992f0ff4a43")
754 c.Assert(err, IsNil)
755 c.Assert(i.Size(), Equals, int64(34))
756 }
757
758 func (s *SuiteDotGit) TestObjects(c *C) {
759 fs := fixtures.ByTag(".git").ByTag("unpacked").One().DotGit()
760 dir := New(fs)
761
762 testObjects(c, fs, dir)
763 testObjectsWithPrefix(c, fs, dir)
764 }
765
766 func (s *SuiteDotGit) TestObjectsExclusive(c *C) {
767 fs := fixtures.ByTag(".git").ByTag("unpacked").One().DotGit()
768 dir := NewWithOptions(fs, Options{ExclusiveAccess: true})
769
770 testObjects(c, fs, dir)
771 testObjectsWithPrefix(c, fs, dir)
772 }
773
774 func testObjects(c *C, _ billy.Filesystem, dir *DotGit) {
775 hashes, err := dir.Objects()
776 c.Assert(err, IsNil)
777 c.Assert(hashes, HasLen, 187)
778 c.Assert(hashes[0].String(), Equals, "0097821d427a3c3385898eb13b50dcbc8702b8a3")
779 c.Assert(hashes[1].String(), Equals, "01d5fa556c33743006de7e76e67a2dfcd994ca04")
780 c.Assert(hashes[2].String(), Equals, "03db8e1fbe133a480f2867aac478fd866686d69e")
781 }
782
783 func testObjectsWithPrefix(c *C, _ billy.Filesystem, dir *DotGit) {
784 prefix, _ := hex.DecodeString("01d5")
785 hashes, err := dir.ObjectsWithPrefix(prefix)
786 c.Assert(err, IsNil)
787 c.Assert(hashes, HasLen, 1)
788 c.Assert(hashes[0].String(), Equals, "01d5fa556c33743006de7e76e67a2dfcd994ca04")
789
790 // Empty prefix should yield all objects.
791 // (subset of testObjects)
792 hashes, err = dir.ObjectsWithPrefix(nil)
793 c.Assert(err, IsNil)
794 c.Assert(hashes, HasLen, 187)
795 }
796
797 func (s *SuiteDotGit) TestObjectsNoFolder(c *C) {
798 fs := s.TemporalFilesystem(c)
799
800 dir := New(fs)
801 hash, err := dir.Objects()
802 c.Assert(err, IsNil)
803 c.Assert(hash, HasLen, 0)
804 }
805
806 func (s *SuiteDotGit) TestObject(c *C) {
807 fs := fixtures.ByTag(".git").ByTag("unpacked").One().DotGit()
808 dir := New(fs)
809
810 hash := plumbing.NewHash("03db8e1fbe133a480f2867aac478fd866686d69e")
811 file, err := dir.Object(hash)
812 c.Assert(err, IsNil)
813 c.Assert(strings.HasSuffix(
814 file.Name(), fs.Join("objects", "03", "db8e1fbe133a480f2867aac478fd866686d69e")),
815 Equals, true,
816 )
817 incomingHash := "9d25e0f9bde9f82882b49fe29117b9411cb157b7" // made up hash
818 incomingDirPath := fs.Join("objects", "tmp_objdir-incoming-123456")
819 incomingFilePath := fs.Join(incomingDirPath, incomingHash[0:2], incomingHash[2:40])
820 fs.MkdirAll(incomingDirPath, os.FileMode(0755))
821 fs.Create(incomingFilePath)
822
823 _, err = dir.Object(plumbing.NewHash(incomingHash))
824 c.Assert(err, IsNil)
825 }
826
827 func (s *SuiteDotGit) TestPreGit235Object(c *C) {
828 fs := fixtures.ByTag(".git").ByTag("unpacked").One().DotGit()
829 dir := New(fs)
830
831 hash := plumbing.NewHash("03db8e1fbe133a480f2867aac478fd866686d69e")
832 file, err := dir.Object(hash)
833 c.Assert(err, IsNil)
834 c.Assert(strings.HasSuffix(
835 file.Name(), fs.Join("objects", "03", "db8e1fbe133a480f2867aac478fd866686d69e")),
836 Equals, true,
837 )
838 incomingHash := "9d25e0f9bde9f82882b49fe29117b9411cb157b7" // made up hash
839 incomingDirPath := fs.Join("objects", "incoming-123456")
840 incomingFilePath := fs.Join(incomingDirPath, incomingHash[0:2], incomingHash[2:40])
841 fs.MkdirAll(incomingDirPath, os.FileMode(0755))
842 fs.Create(incomingFilePath)
843
844 _, err = dir.Object(plumbing.NewHash(incomingHash))
845 c.Assert(err, IsNil)
846 }
847
848 func (s *SuiteDotGit) TestObjectStat(c *C) {
849 fs := fixtures.ByTag(".git").ByTag("unpacked").One().DotGit()
850 dir := New(fs)
851
852 hash := plumbing.NewHash("03db8e1fbe133a480f2867aac478fd866686d69e")
853 _, err := dir.ObjectStat(hash)
854 c.Assert(err, IsNil)
855 incomingHash := "9d25e0f9bde9f82882b49fe29117b9411cb157b7" // made up hash
856 incomingDirPath := fs.Join("objects", "tmp_objdir-incoming-123456")
857 incomingFilePath := fs.Join(incomingDirPath, incomingHash[0:2], incomingHash[2:40])
858 fs.MkdirAll(incomingDirPath, os.FileMode(0755))
859 fs.Create(incomingFilePath)
860
861 _, err = dir.ObjectStat(plumbing.NewHash(incomingHash))
862 c.Assert(err, IsNil)
863 }
864
865 func (s *SuiteDotGit) TestObjectDelete(c *C) {
866 fs := fixtures.ByTag(".git").ByTag("unpacked").One().DotGit()
867 dir := New(fs)
868
869 hash := plumbing.NewHash("03db8e1fbe133a480f2867aac478fd866686d69e")
870 err := dir.ObjectDelete(hash)
871 c.Assert(err, IsNil)
872
873 incomingHash := "9d25e0f9bde9f82882b49fe29117b9411cb157b7" // made up hash
874 incomingDirPath := fs.Join("objects", "tmp_objdir-incoming-123456")
875 incomingSubDirPath := fs.Join(incomingDirPath, incomingHash[0:2])
876 incomingFilePath := fs.Join(incomingSubDirPath, incomingHash[2:40])
877
878 err = fs.MkdirAll(incomingSubDirPath, os.FileMode(0755))
879 c.Assert(err, IsNil)
880
881 f, err := fs.Create(incomingFilePath)
882 c.Assert(err, IsNil)
883
884 err = f.Close()
885 c.Assert(err, IsNil)
886
887 err = dir.ObjectDelete(plumbing.NewHash(incomingHash))
888 c.Assert(err, IsNil)
889 }
890
891 func (s *SuiteDotGit) TestObjectNotFound(c *C) {
892 fs := fixtures.ByTag(".git").ByTag("unpacked").One().DotGit()
893 dir := New(fs)
894
895 hash := plumbing.NewHash("not-found-object")
896 file, err := dir.Object(hash)
897 c.Assert(err, NotNil)
898 c.Assert(file, IsNil)
899 }
900
901 func (s *SuiteDotGit) TestSubmodules(c *C) {
902 fs := fixtures.ByTag("submodule").One().DotGit()
903 dir := New(fs)
904
905 m, err := dir.Module("basic")
906 c.Assert(err, IsNil)
907 c.Assert(strings.HasSuffix(m.Root(), m.Join(".git", "modules", "basic")), Equals, true)
908 }
909
910 func (s *SuiteDotGit) TestPackRefs(c *C) {
911 fs := s.TemporalFilesystem(c)
912
913 dir := New(fs)
914
915 err := dir.SetRef(plumbing.NewReferenceFromStrings(
916 "refs/heads/foo",
917 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
918 ), nil)
919 c.Assert(err, IsNil)
920 err = dir.SetRef(plumbing.NewReferenceFromStrings(
921 "refs/heads/bar",
922 "a8d3ffab552895c19b9fcf7aa264d277cde33881",
923 ), nil)
924 c.Assert(err, IsNil)
925
926 refs, err := dir.Refs()
927 c.Assert(err, IsNil)
928 c.Assert(refs, HasLen, 2)
929 looseCount, err := dir.CountLooseRefs()
930 c.Assert(err, IsNil)
931 c.Assert(looseCount, Equals, 2)
932
933 err = dir.PackRefs()
934 c.Assert(err, IsNil)
935
936 // Make sure the refs are still there, but no longer loose.
937 refs, err = dir.Refs()
938 c.Assert(err, IsNil)
939 c.Assert(refs, HasLen, 2)
940 looseCount, err = dir.CountLooseRefs()
941 c.Assert(err, IsNil)
942 c.Assert(looseCount, Equals, 0)
943
944 ref, err := dir.Ref("refs/heads/foo")
945 c.Assert(err, IsNil)
946 c.Assert(ref, NotNil)
947 c.Assert(ref.Hash().String(), Equals, "e8d3ffab552895c19b9fcf7aa264d277cde33881")
948 ref, err = dir.Ref("refs/heads/bar")
949 c.Assert(err, IsNil)
950 c.Assert(ref, NotNil)
951 c.Assert(ref.Hash().String(), Equals, "a8d3ffab552895c19b9fcf7aa264d277cde33881")
952
953 // Now update one of them, re-pack, and check again.
954 err = dir.SetRef(plumbing.NewReferenceFromStrings(
955 "refs/heads/foo",
956 "b8d3ffab552895c19b9fcf7aa264d277cde33881",
957 ), nil)
958 c.Assert(err, IsNil)
959 looseCount, err = dir.CountLooseRefs()
960 c.Assert(err, IsNil)
961 c.Assert(looseCount, Equals, 1)
962 err = dir.PackRefs()
963 c.Assert(err, IsNil)
964
965 // Make sure the refs are still there, but no longer loose.
966 refs, err = dir.Refs()
967 c.Assert(err, IsNil)
968 c.Assert(refs, HasLen, 2)
969 looseCount, err = dir.CountLooseRefs()
970 c.Assert(err, IsNil)
971 c.Assert(looseCount, Equals, 0)
972
973 ref, err = dir.Ref("refs/heads/foo")
974 c.Assert(err, IsNil)
975 c.Assert(ref, NotNil)
976 c.Assert(ref.Hash().String(), Equals, "b8d3ffab552895c19b9fcf7aa264d277cde33881")
977 }
978
979 func TestAlternatesDefault(t *testing.T) {
980 // Create a new dotgit object.
981 dotFS := osfs.New(t.TempDir())
982
983 testAlternates(t, dotFS, dotFS)
984 }
985
986 func TestAlternatesWithFS(t *testing.T) {
987 // Create a new dotgit object with a specific FS for alternates.
988 altFS := osfs.New(t.TempDir())
989 dotFS, _ := altFS.Chroot("repo2")
990
991 testAlternates(t, dotFS, altFS)
992 }
993
994 func TestAlternatesWithBoundOS(t *testing.T) {
995 // Create a new dotgit object with a specific FS for alternates.
996 altFS := osfs.New(t.TempDir(), osfs.WithBoundOS())
997 dotFS, _ := altFS.Chroot("repo2")
998
999 testAlternates(t, dotFS, altFS)
1000 }
1001
1002 func testAlternates(t *testing.T, dotFS, altFS billy.Filesystem) {
1003 tests := []struct {
1004 name string
1005 in []string
1006 inWindows []string
1007 setup func()
1008 wantErr bool
1009 wantRoots []string
1010 }{
1011 {
1012 name: "no alternates",
1013 },
1014 {
1015 name: "abs path",
1016 in: []string{filepath.Join(altFS.Root(), "./repo1/.git/objects")},
1017 inWindows: []string{filepath.Join(altFS.Root(), ".\\repo1\\.git\\objects")},
1018 setup: func() {
1019 err := altFS.MkdirAll(filepath.Join("repo1", ".git", "objects"), 0o700)
1020 assert.NoError(t, err)
1021 },
1022 wantRoots: []string{filepath.Join("repo1", ".git")},
1023 },
1024 {
1025 name: "rel path",
1026 in: []string{"../../../repo3//.git/objects"},
1027 inWindows: []string{"..\\..\\..\\repo3\\.git\\objects"},
1028 setup: func() {
1029 err := altFS.MkdirAll(filepath.Join("repo3", ".git", "objects"), 0o700)
1030 assert.NoError(t, err)
1031 },
1032 wantRoots: []string{filepath.Join("repo3", ".git")},
1033 },
1034 {
1035 name: "invalid abs path",
1036 in: []string{"/alt/target2"},
1037 inWindows: []string{"\\alt\\target2"},
1038 wantErr: true,
1039 },
1040 {
1041 name: "invalid rel path",
1042 in: []string{"../../../alt/target3"},
1043 inWindows: []string{"..\\..\\..\\alt\\target3"},
1044 wantErr: true,
1045 },
1046 }
1047
1048 for _, tc := range tests {
1049 t.Run(tc.name, func(t *testing.T) {
1050 dir := NewWithOptions(dotFS, Options{AlternatesFS: altFS})
1051 err := dir.Initialize()
1052 assert.NoError(t, err)
1053
1054 content := strings.Join(tc.in, "\n")
1055 if runtime.GOOS == "windows" {
1056 content = strings.Join(tc.inWindows, "\r\n")
1057 }
1058
1059 // Create alternates file.
1060 altpath := dotFS.Join("objects", "info", "alternates")
1061 f, err := dotFS.Create(altpath)
1062 assert.NoError(t, err)
1063 f.Write([]byte(content))
1064 f.Close()
1065
1066 if tc.setup != nil {
1067 tc.setup()
1068 }
1069
1070 dotgits, err := dir.Alternates()
1071 if tc.wantErr {
1072 assert.Error(t, err)
1073 } else {
1074 assert.NoError(t, err)
1075 }
1076
1077 for i, d := range dotgits {
1078 assert.Regexp(t, "^"+regexp.QuoteMeta(altFS.Root()), d.fs.Root())
1079 assert.Regexp(t, regexp.QuoteMeta(tc.wantRoots[i])+"$", d.fs.Root())
1080 }
1081 })
1082 }
1083 }
1084
1085 func TestAlternatesDupes(t *testing.T) {
1086 dotFS := osfs.New(t.TempDir())
1087 dir := New(dotFS)
1088 err := dir.Initialize()
1089 assert.NoError(t, err)
1090
1091 path := filepath.Join(dotFS.Root(), "target3")
1092 dupes := []string{path, path, path, path, path}
1093
1094 content := strings.Join(dupes, "\n")
1095 if runtime.GOOS == "windows" {
1096 content = strings.Join(dupes, "\r\n")
1097 }
1098
1099 err = dotFS.MkdirAll("target3", 0o700)
1100 assert.NoError(t, err)
1101
1102 // Create alternates file.
1103 altpath := dotFS.Join("objects", "info", "alternates")
1104 f, err := dotFS.Create(altpath)
1105 assert.NoError(t, err)
1106 f.Write([]byte(content))
1107 f.Close()
1108
1109 dotgits, err := dir.Alternates()
1110 assert.NoError(t, err)
1111 assert.Len(t, dotgits, 1)
1112 }
1113
1114 type norwfs struct {
1115 billy.Filesystem
1116 }
1117
1118 func (f *norwfs) Capabilities() billy.Capability {
1119 return billy.Capabilities(f.Filesystem) &^ billy.ReadAndWriteCapability
1120 }
1121
1122 func (s *SuiteDotGit) TestIncBytes(c *C) {
1123 tests := []struct {
1124 in []byte
1125 out []byte
1126 overflow bool
1127 }{
1128 {[]byte{0}, []byte{1}, false},
1129 {[]byte{0xff}, []byte{0}, true},
1130 {[]byte{7, 0xff}, []byte{8, 0}, false},
1131 {[]byte{0xff, 0xff}, []byte{0, 0}, true},
1132 }
1133 for _, test := range tests {
1134 out, overflow := incBytes(test.in)
1135 c.Assert(out, DeepEquals, test.out)
1136 c.Assert(overflow, Equals, test.overflow)
1137 }
1138 }
1139
1140 // this filesystem wrapper returns os.ErrNotExist if the file matches
1141 // the provided paths list
1142 type notExistsFS struct {
1143 billy.Filesystem
1144
1145 paths []string
1146 }
1147
1148 func (f *notExistsFS) matches(path string) bool {
1149 p := filepath.ToSlash(path)
1150 for _, n := range f.paths {
1151 if p == n {
1152 return true
1153 }
1154 }
1155 return false
1156 }
1157
1158 func (f *notExistsFS) Open(filename string) (billy.File, error) {
1159 if f.matches(filename) {
1160 return nil, os.ErrNotExist
1161 }
1162
1163 return f.Filesystem.Open(filename)
1164 }
1165
1166 func (f *notExistsFS) ReadDir(path string) ([]os.FileInfo, error) {
1167 if f.matches(path) {
1168 return nil, os.ErrNotExist
1169 }
1170
1171 return f.Filesystem.ReadDir(path)
1172 }
1173
1174 func (s *SuiteDotGit) TestDeletedRefs(c *C) {
1175 fs := s.TemporalFilesystem(c)
1176
1177 dir := New(&notExistsFS{
1178 Filesystem: fs,
1179 paths: []string{
1180 "refs/heads/bar",
1181 "refs/heads/baz",
1182 },
1183 })
1184
1185 err := dir.SetRef(plumbing.NewReferenceFromStrings(
1186 "refs/heads/foo",
1187 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
1188 ), nil)
1189 c.Assert(err, IsNil)
1190 err = dir.SetRef(plumbing.NewReferenceFromStrings(
1191 "refs/heads/bar",
1192 "a8d3ffab552895c19b9fcf7aa264d277cde33881",
1193 ), nil)
1194 c.Assert(err, IsNil)
1195 err = dir.SetRef(plumbing.NewReferenceFromStrings(
1196 "refs/heads/baz/baz",
1197 "a8d3ffab552895c19b9fcf7aa264d277cde33881",
1198 ), nil)
1199 c.Assert(err, IsNil)
1200
1201 refs, err := dir.Refs()
1202 c.Assert(err, IsNil)
1203 c.Assert(refs, HasLen, 1)
1204 c.Assert(refs[0].Name(), Equals, plumbing.ReferenceName("refs/heads/foo"))
1205 }
1206
1207 // Checks that setting a reference that has been packed and checking its old value is successful
1208 func (s *SuiteDotGit) TestSetPackedRef(c *C) {
1209 fs := s.TemporalFilesystem(c)
1210
1211 dir := New(fs)
1212
1213 err := dir.SetRef(plumbing.NewReferenceFromStrings(
1214 "refs/heads/foo",
1215 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
1216 ), nil)
1217 c.Assert(err, IsNil)
1218
1219 refs, err := dir.Refs()
1220 c.Assert(err, IsNil)
1221 c.Assert(refs, HasLen, 1)
1222 looseCount, err := dir.CountLooseRefs()
1223 c.Assert(err, IsNil)
1224 c.Assert(looseCount, Equals, 1)
1225
1226 err = dir.PackRefs()
1227 c.Assert(err, IsNil)
1228
1229 // Make sure the refs are still there, but no longer loose.
1230 refs, err = dir.Refs()
1231 c.Assert(err, IsNil)
1232 c.Assert(refs, HasLen, 1)
1233 looseCount, err = dir.CountLooseRefs()
1234 c.Assert(err, IsNil)
1235 c.Assert(looseCount, Equals, 0)
1236
1237 ref, err := dir.Ref("refs/heads/foo")
1238 c.Assert(err, IsNil)
1239 c.Assert(ref, NotNil)
1240 c.Assert(ref.Hash().String(), Equals, "e8d3ffab552895c19b9fcf7aa264d277cde33881")
1241
1242 // Attempt to update the reference using an invalid old reference value
1243 err = dir.SetRef(plumbing.NewReferenceFromStrings(
1244 "refs/heads/foo",
1245 "b8d3ffab552895c19b9fcf7aa264d277cde33881",
1246 ), plumbing.NewReferenceFromStrings(
1247 "refs/heads/foo",
1248 "e8d3ffab552895c19b9fcf7aa264d277cde33882",
1249 ))
1250 c.Assert(err, Equals, storage.ErrReferenceHasChanged)
1251
1252 // Now update the reference and it should pass
1253 err = dir.SetRef(plumbing.NewReferenceFromStrings(
1254 "refs/heads/foo",
1255 "b8d3ffab552895c19b9fcf7aa264d277cde33881",
1256 ), plumbing.NewReferenceFromStrings(
1257 "refs/heads/foo",
1258 "e8d3ffab552895c19b9fcf7aa264d277cde33881",
1259 ))
1260 c.Assert(err, IsNil)
1261 looseCount, err = dir.CountLooseRefs()
1262 c.Assert(err, IsNil)
1263 c.Assert(looseCount, Equals, 1)
1264 }
1265
1266 func TestIssue55(t *testing.T) {
1267 t.Parallel()
1268
1269 writeObject := func(fs billy.Filesystem) {
1270 t.Helper()
1271
1272 dir := New(fs)
1273 err := dir.Initialize()
1274 require.NoError(t, err)
1275
1276 w, err := dir.NewObject()
1277 require.NoError(t, err)
1278
1279 err = w.WriteHeader(plumbing.BlobObject, 14)
1280 require.NoError(t, err)
1281 n, err := w.Write([]byte("this is a test"))
1282 require.NoError(t, err)
1283 assert.Equal(t, 14, n)
1284
1285 assert.Equal(t, "a8a940627d132695a9769df883f85992f0ff4a43", w.Hash().String())
1286
1287 err = w.Close()
1288 require.NoError(t, err)
1289 }
1290
1291 for _, tc := range []struct {
1292 name string
1293 fs billy.Filesystem
1294 }{
1295 {"BoundOS", osfs.New(t.TempDir(), osfs.WithBoundOS())},
1296 {"ChrootOS", osfs.New(t.TempDir(), osfs.WithChrootOS())},
1297 } {
1298 t.Run(tc.name, func(t *testing.T) {
1299 t.Parallel()
1300 path := filepath.Join("objects", "a8", "a940627d132695a9769df883f85992f0ff4a43")
1301
1302 writeObject(tc.fs)
1303 i, err := tc.fs.Stat(path)
1304 require.NoError(t, err)
1305 assert.Equal(t, int64(34), i.Size())
1306
1307 ro, err := isReadOnly(tc.fs, path)
1308 require.NoError(t, err)
1309 assert.True(t, ro, "file %q is not read-only", path)
1310
1311 // Recreate the same object.
1312 writeObject(tc.fs)
1313 i, err = tc.fs.Stat(path)
1314 require.NoError(t, err)
1315 assert.Equal(t, int64(34), i.Size())
1316
1317 ro, err = isReadOnly(tc.fs, path)
1318 require.NoError(t, err)
1319 assert.True(t, ro, "file %q is not read-only", path)
1320 })
1321 }
1322 }