Debian Codegraph @

storage/filesystem/dotgit/dotgit.go

raw
1 // https://github.com/git/git/blob/master/Documentation/gitrepository-layout.txt
2 package dotgit
3
4 import (
5 "bufio"
6 "bytes"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "path"
12 "path/filepath"
13 "reflect"
14 "runtime"
15 "sort"
16 "strings"
17 "time"
18
19 "github.com/go-git/go-git/v5/internal/pathutil"
20 "github.com/go-git/go-git/v5/plumbing"
21 "github.com/go-git/go-git/v5/plumbing/hash"
22 "github.com/go-git/go-git/v5/storage"
23 "github.com/go-git/go-git/v5/utils/ioutil"
24
25 "github.com/go-git/go-billy/v5"
26 "github.com/go-git/go-billy/v5/helper/chroot"
27 )
28
29 const (
30 suffix = ".git"
31 packedRefsPath = "packed-refs"
32 configPath = "config"
33 indexPath = "index"
34 shallowPath = "shallow"
35 modulePath = "modules"
36 objectsPath = "objects"
37 packPath = "pack"
38 refsPath = "refs"
39 branchesPath = "branches"
40 hooksPath = "hooks"
41 infoPath = "info"
42 remotesPath = "remotes"
43 logsPath = "logs"
44 worktreesPath = "worktrees"
45 alternatesPath = "alternates"
46
47 tmpPackedRefsPrefix = "._packed-refs"
48
49 packPrefix = "pack-"
50 packExt = ".pack"
51 idxExt = ".idx"
52 )
53
54 var (
55 // ErrNotFound is returned by New when the path is not found.
56 ErrNotFound = errors.New("path not found")
57 // ErrIdxNotFound is returned by Idxfile when the idx file is not found
58 ErrIdxNotFound = errors.New("idx file not found")
59 // ErrPackfileNotFound is returned by Packfile when the packfile is not found
60 ErrPackfileNotFound = errors.New("packfile not found")
61 // ErrConfigNotFound is returned by Config when the config is not found
62 ErrConfigNotFound = errors.New("config file not found")
63 // ErrPackedRefsDuplicatedRef is returned when a duplicated reference is
64 // found in the packed-ref file. This is usually the case for corrupted git
65 // repositories.
66 ErrPackedRefsDuplicatedRef = errors.New("duplicated ref found in packed-ref file")
67 // ErrPackedRefsBadFormat is returned when the packed-ref file corrupt.
68 ErrPackedRefsBadFormat = errors.New("malformed packed-ref")
69 // ErrSymRefTargetNotFound is returned when a symbolic reference is
70 // targeting a non-existing object. This usually means the repository
71 // is corrupt.
72 ErrSymRefTargetNotFound = errors.New("symbolic reference target not found")
73 // ErrIsDir is returned when a reference file is attempting to be read,
74 // but the path specified is a directory.
75 ErrIsDir = errors.New("reference path is a directory")
76 // ErrEmptyRefFile is returned when a reference file is attempted to be read,
77 // but the file is empty
78 ErrEmptyRefFile = errors.New("ref file is empty")
79 // ErrModuleNameEscape is returned when a submodule name would
80 // resolve outside the modules/ subtree, mirroring canonical Git's
81 // "ignoring suspicious submodule name" defence.
82 ErrModuleNameEscape = errors.New("submodule name escapes modules/ directory")
83 // ErrReferenceNameEscape is returned when a reference name would
84 // resolve outside its reference sub-tree once turned into a path
85 // under the .git directory (e.g. a name with a ".." component).
86 ErrReferenceNameEscape = errors.New("reference name escapes the reference storage")
87 )
88
89 // isPathSep reports whether r is a path separator in reference names.
90 // It treats both '/' and '\\' as separators to harden against cross-OS paths.
91 func isPathSep(r rune) bool { return r == '/' || r == '\\' }
92
93 // validReferenceName rejects reference names that cannot be safely turned into
94 // a path under the .git directory. A loose reference is stored verbatim at
95 // ".git/<name>", so a crafted name — for instance one advertised by a malicious
96 // remote — could climb out of its reference sub-tree and read, overwrite, or
97 // delete unrelated metadata such as .git/config.
98 //
99 // The storage-safety gate is plumbing.ReferenceName.IsSafe, mirroring Git's
100 // refname_is_safe: a name must be under refs/ without escaping it, or be a
101 // [A-Z_] pseudo-ref. This alone rejects absolute, drive-prefixed, escaping and
102 // single-level metadata names. On top of it, this adds filesystem-specific
103 // hardening that IsSafe's literal check does not cover: control characters, and
104 // components a case-insensitive/NTFS/HFS+ filesystem would fold back to "." or
105 // ".." (trailing dots/spaces, Alternate Data Streams, ignorable Unicode code
106 // points), delegated to pathutil.IsHFSDot and pathutil.IsNTFSDot with "." as
107 // the needle — as validSubmoduleName does — and run regardless of host OS.
108 func validReferenceName(name plumbing.ReferenceName) error {
109 if !name.IsSafe() {
110 return fmt.Errorf("%w: %q is not under refs/ nor a valid pseudo-ref", ErrReferenceNameEscape, string(name))
111 }
112
113 s := string(name)
114 for i := 0; i < len(s); i++ {
115 if s[i] < 0x20 || s[i] == 0x7f {
116 return fmt.Errorf("%w: %q", ErrReferenceNameEscape, s)
117 }
118 }
119 for _, part := range strings.FieldsFunc(s, isPathSep) {
120 // IsNTFSDot/IsHFSDot with a "." needle match ".." and its disguises
121 // but not a bare ".", so reject that component explicitly too.
122 if part == "." || pathutil.IsHFSDot(part, ".") || pathutil.IsNTFSDot(part, ".", "") {
123 return fmt.Errorf("%w: %q", ErrReferenceNameEscape, s)
124 }
125 }
126 return nil
127 }
128
129 // Options holds configuration for the storage.
130 type Options struct {
131 // ExclusiveAccess means that the filesystem is not modified externally
132 // while the repo is open.
133 ExclusiveAccess bool
134 // KeepDescriptors makes the file descriptors to be reused but they will
135 // need to be manually closed calling Close().
136 KeepDescriptors bool
137 // AlternatesFS provides the billy filesystem to be used for Git Alternates.
138 // If none is provided, it falls back to using the underlying instance used for
139 // DotGit.
140 AlternatesFS billy.Filesystem
141 }
142
143 // The DotGit type represents a local git repository on disk. This
144 // type is not zero-value-safe, use the New function to initialize it.
145 type DotGit struct {
146 options Options
147 fs billy.Filesystem
148
149 // incoming object directory information
150 incomingChecked bool
151 incomingDirName string
152
153 objectList []plumbing.Hash // sorted
154 objectMap map[plumbing.Hash]struct{}
155 packList []plumbing.Hash
156 packMap map[plumbing.Hash]struct{}
157
158 files map[plumbing.Hash]billy.File
159 }
160
161 // New returns a DotGit value ready to be used. The path argument must
162 // be the absolute path of a git repository directory (e.g.
163 // "/foo/bar/.git").
164 func New(fs billy.Filesystem) *DotGit {
165 return NewWithOptions(fs, Options{})
166 }
167
168 // NewWithOptions sets non default configuration options.
169 // See New for complete help.
170 func NewWithOptions(fs billy.Filesystem, o Options) *DotGit {
171 return &DotGit{
172 options: o,
173 fs: fs,
174 }
175 }
176
177 // Initialize creates all the folder scaffolding.
178 func (d *DotGit) Initialize() error {
179 mustExists := []string{
180 d.fs.Join("objects", "info"),
181 d.fs.Join("objects", "pack"),
182 d.fs.Join("refs", "heads"),
183 d.fs.Join("refs", "tags"),
184 }
185
186 for _, path := range mustExists {
187 _, err := d.fs.Stat(path)
188 if err == nil {
189 continue
190 }
191
192 if !os.IsNotExist(err) {
193 return err
194 }
195
196 if err := d.fs.MkdirAll(path, os.ModeDir|os.ModePerm); err != nil {
197 return err
198 }
199 }
200
201 return nil
202 }
203
204 // Close closes all opened files.
205 func (d *DotGit) Close() error {
206 var firstError error
207 if d.files != nil {
208 for _, f := range d.files {
209 err := f.Close()
210 if err != nil && firstError == nil {
211 firstError = err
212 continue
213 }
214 }
215
216 d.files = nil
217 }
218
219 if firstError != nil {
220 return firstError
221 }
222
223 return nil
224 }
225
226 // ConfigWriter returns a file pointer for write to the config file
227 func (d *DotGit) ConfigWriter() (billy.File, error) {
228 return d.fs.Create(configPath)
229 }
230
231 // Config returns a file pointer for read to the config file
232 func (d *DotGit) Config() (billy.File, error) {
233 return d.fs.Open(configPath)
234 }
235
236 // IndexWriter returns a file pointer for write to the index file
237 func (d *DotGit) IndexWriter() (billy.File, error) {
238 return d.fs.Create(indexPath)
239 }
240
241 // Index returns a file pointer for read to the index file
242 func (d *DotGit) Index() (billy.File, error) {
243 return d.fs.Open(indexPath)
244 }
245
246 // ShallowWriter returns a file pointer for write to the shallow file
247 func (d *DotGit) ShallowWriter() (billy.File, error) {
248 return d.fs.Create(shallowPath)
249 }
250
251 // Shallow returns a file pointer for read to the shallow file
252 func (d *DotGit) Shallow() (billy.File, error) {
253 f, err := d.fs.Open(shallowPath)
254 if err != nil {
255 if os.IsNotExist(err) {
256 return nil, nil
257 }
258
259 return nil, err
260 }
261
262 return f, nil
263 }
264
265 // NewObjectPack return a writer for a new packfile, it saves the packfile to
266 // disk and also generates and save the index for the given packfile.
267 func (d *DotGit) NewObjectPack() (*PackWriter, error) {
268 d.cleanPackList()
269 return newPackWrite(d.fs)
270 }
271
272 // ObjectPacks returns the list of availables packfiles
273 func (d *DotGit) ObjectPacks() ([]plumbing.Hash, error) {
274 if !d.options.ExclusiveAccess {
275 return d.objectPacks()
276 }
277
278 err := d.genPackList()
279 if err != nil {
280 return nil, err
281 }
282
283 return d.packList, nil
284 }
285
286 func (d *DotGit) objectPacks() ([]plumbing.Hash, error) {
287 packDir := d.fs.Join(objectsPath, packPath)
288 files, err := d.fs.ReadDir(packDir)
289 if err != nil {
290 if os.IsNotExist(err) {
291 return nil, nil
292 }
293
294 return nil, err
295 }
296
297 var packs []plumbing.Hash
298 for _, f := range files {
299 n := f.Name()
300 if !strings.HasSuffix(n, packExt) || !strings.HasPrefix(n, packPrefix) {
301 continue
302 }
303
304 h := plumbing.NewHash(n[5 : len(n)-5]) // pack-(hash).pack
305 if h.IsZero() {
306 // Ignore files with badly-formatted names.
307 continue
308 }
309 packs = append(packs, h)
310 }
311
312 return packs, nil
313 }
314
315 func (d *DotGit) objectPackPath(hash plumbing.Hash, extension string) string {
316 return d.fs.Join(objectsPath, packPath, fmt.Sprintf("pack-%s.%s", hash.String(), extension))
317 }
318
319 func (d *DotGit) objectPackOpen(hash plumbing.Hash, extension string) (billy.File, error) {
320 if d.options.KeepDescriptors && extension == "pack" {
321 if d.files == nil {
322 d.files = make(map[plumbing.Hash]billy.File)
323 }
324
325 f, ok := d.files[hash]
326 if ok {
327 return f, nil
328 }
329 }
330
331 err := d.hasPack(hash)
332 if err != nil {
333 return nil, err
334 }
335
336 path := d.objectPackPath(hash, extension)
337 pack, err := d.fs.Open(path)
338 if err != nil {
339 if os.IsNotExist(err) {
340 return nil, ErrPackfileNotFound
341 }
342
343 return nil, err
344 }
345
346 if d.options.KeepDescriptors && extension == "pack" {
347 d.files[hash] = pack
348 }
349
350 return pack, nil
351 }
352
353 // ObjectPack returns a fs.File of the given packfile
354 func (d *DotGit) ObjectPack(hash plumbing.Hash) (billy.File, error) {
355 err := d.hasPack(hash)
356 if err != nil {
357 return nil, err
358 }
359
360 return d.objectPackOpen(hash, `pack`)
361 }
362
363 // ObjectPackIdx returns a fs.File of the index file for a given packfile
364 func (d *DotGit) ObjectPackIdx(hash plumbing.Hash) (billy.File, error) {
365 err := d.hasPack(hash)
366 if err != nil {
367 return nil, err
368 }
369
370 return d.objectPackOpen(hash, `idx`)
371 }
372
373 func (d *DotGit) DeleteOldObjectPackAndIndex(hash plumbing.Hash, t time.Time) error {
374 d.cleanPackList()
375
376 path := d.objectPackPath(hash, `pack`)
377 if !t.IsZero() {
378 fi, err := d.fs.Stat(path)
379 if err != nil {
380 return err
381 }
382 // too new, skip deletion.
383 if !fi.ModTime().Before(t) {
384 return nil
385 }
386 }
387 err := d.fs.Remove(path)
388 if err != nil {
389 return err
390 }
391 return d.fs.Remove(d.objectPackPath(hash, `idx`))
392 }
393
394 // NewObject return a writer for a new object file.
395 func (d *DotGit) NewObject() (*ObjectWriter, error) {
396 d.cleanObjectList()
397
398 return newObjectWriter(d.fs)
399 }
400
401 // ObjectsWithPrefix returns the hashes of objects that have the given prefix.
402 func (d *DotGit) ObjectsWithPrefix(prefix []byte) ([]plumbing.Hash, error) {
403 // Handle edge cases.
404 if len(prefix) < 1 {
405 return d.Objects()
406 } else if len(prefix) > len(plumbing.ZeroHash) {
407 return nil, nil
408 }
409
410 if d.options.ExclusiveAccess {
411 err := d.genObjectList()
412 if err != nil {
413 return nil, err
414 }
415
416 // Rely on d.objectList being sorted.
417 // Figure out the half-open interval defined by the prefix.
418 first := sort.Search(len(d.objectList), func(i int) bool {
419 // Same as plumbing.HashSlice.Less.
420 return bytes.Compare(d.objectList[i][:], prefix) >= 0
421 })
422 lim := len(d.objectList)
423 if limPrefix, overflow := incBytes(prefix); !overflow {
424 lim = sort.Search(len(d.objectList), func(i int) bool {
425 // Same as plumbing.HashSlice.Less.
426 return bytes.Compare(d.objectList[i][:], limPrefix) >= 0
427 })
428 }
429 return d.objectList[first:lim], nil
430 }
431
432 // This is the slow path.
433 var objects []plumbing.Hash
434 var n int
435 err := d.ForEachObjectHash(func(hash plumbing.Hash) error {
436 n++
437 if bytes.HasPrefix(hash[:], prefix) {
438 objects = append(objects, hash)
439 }
440 return nil
441 })
442 if err != nil {
443 return nil, err
444 }
445 return objects, nil
446 }
447
448 // Objects returns a slice with the hashes of objects found under the
449 // .git/objects/ directory.
450 func (d *DotGit) Objects() ([]plumbing.Hash, error) {
451 if d.options.ExclusiveAccess {
452 err := d.genObjectList()
453 if err != nil {
454 return nil, err
455 }
456
457 return d.objectList, nil
458 }
459
460 var objects []plumbing.Hash
461 err := d.ForEachObjectHash(func(hash plumbing.Hash) error {
462 objects = append(objects, hash)
463 return nil
464 })
465 if err != nil {
466 return nil, err
467 }
468 return objects, nil
469 }
470
471 // ForEachObjectHash iterates over the hashes of objects found under the
472 // .git/objects/ directory and executes the provided function.
473 func (d *DotGit) ForEachObjectHash(fun func(plumbing.Hash) error) error {
474 if !d.options.ExclusiveAccess {
475 return d.forEachObjectHash(fun)
476 }
477
478 err := d.genObjectList()
479 if err != nil {
480 return err
481 }
482
483 for _, h := range d.objectList {
484 err := fun(h)
485 if err != nil {
486 return err
487 }
488 }
489
490 return nil
491 }
492
493 func (d *DotGit) forEachObjectHash(fun func(plumbing.Hash) error) error {
494 files, err := d.fs.ReadDir(objectsPath)
495 if err != nil {
496 if os.IsNotExist(err) {
497 return nil
498 }
499
500 return err
501 }
502
503 for _, f := range files {
504 if f.IsDir() && len(f.Name()) == 2 && isHex(f.Name()) {
505 base := f.Name()
506 d, err := d.fs.ReadDir(d.fs.Join(objectsPath, base))
507 if err != nil {
508 return err
509 }
510
511 for _, o := range d {
512 h := plumbing.NewHash(base + o.Name())
513 if h.IsZero() {
514 // Ignore files with badly-formatted names.
515 continue
516 }
517 err = fun(h)
518 if err != nil {
519 return err
520 }
521 }
522 }
523 }
524
525 return nil
526 }
527
528 func (d *DotGit) cleanObjectList() {
529 d.objectMap = nil
530 d.objectList = nil
531 }
532
533 func (d *DotGit) genObjectList() error {
534 if d.objectMap != nil {
535 return nil
536 }
537
538 d.objectMap = make(map[plumbing.Hash]struct{})
539 populate := func(h plumbing.Hash) error {
540 d.objectList = append(d.objectList, h)
541 d.objectMap[h] = struct{}{}
542
543 return nil
544 }
545 if err := d.forEachObjectHash(populate); err != nil {
546 return err
547 }
548 plumbing.HashesSort(d.objectList)
549 return nil
550 }
551
552 func (d *DotGit) hasObject(h plumbing.Hash) error {
553 if !d.options.ExclusiveAccess {
554 return nil
555 }
556
557 err := d.genObjectList()
558 if err != nil {
559 return err
560 }
561
562 _, ok := d.objectMap[h]
563 if !ok {
564 return plumbing.ErrObjectNotFound
565 }
566
567 return nil
568 }
569
570 func (d *DotGit) cleanPackList() {
571 d.packMap = nil
572 d.packList = nil
573 }
574
575 func (d *DotGit) genPackList() error {
576 if d.packMap != nil {
577 return nil
578 }
579
580 op, err := d.objectPacks()
581 if err != nil {
582 return err
583 }
584
585 d.packMap = make(map[plumbing.Hash]struct{})
586 d.packList = nil
587
588 for _, h := range op {
589 d.packList = append(d.packList, h)
590 d.packMap[h] = struct{}{}
591 }
592
593 return nil
594 }
595
596 func (d *DotGit) hasPack(h plumbing.Hash) error {
597 if !d.options.ExclusiveAccess {
598 return nil
599 }
600
601 err := d.genPackList()
602 if err != nil {
603 return err
604 }
605
606 _, ok := d.packMap[h]
607 if !ok {
608 return ErrPackfileNotFound
609 }
610
611 return nil
612 }
613
614 func (d *DotGit) objectPath(h plumbing.Hash) string {
615 hex := h.String()
616 return d.fs.Join(objectsPath, hex[0:2], hex[2:hash.HexSize])
617 }
618
619 // incomingObjectPath is intended to add support for a git pre-receive hook
620 // to be written it adds support for go-git to find objects in an "incoming"
621 // directory, so that the library can be used to write a pre-receive hook
622 // that deals with the incoming objects.
623 //
624 // More on git hooks found here : https://git-scm.com/docs/githooks
625 // More on 'quarantine'/incoming directory here:
626 //
627 // https://git-scm.com/docs/git-receive-pack
628 func (d *DotGit) incomingObjectPath(h plumbing.Hash) string {
629 hString := h.String()
630
631 if d.incomingDirName == "" {
632 return d.fs.Join(objectsPath, hString[0:2], hString[2:hash.HexSize])
633 }
634
635 return d.fs.Join(objectsPath, d.incomingDirName, hString[0:2], hString[2:hash.HexSize])
636 }
637
638 // hasIncomingObjects searches for an incoming directory and keeps its name
639 // so it doesn't have to be found each time an object is accessed.
640 func (d *DotGit) hasIncomingObjects() bool {
641 if !d.incomingChecked {
642 directoryContents, err := d.fs.ReadDir(objectsPath)
643 if err == nil {
644 for _, file := range directoryContents {
645 if file.IsDir() && (strings.HasPrefix(file.Name(), "tmp_objdir-incoming-") ||
646 // Before Git 2.35 incoming commits directory had another prefix
647 strings.HasPrefix(file.Name(), "incoming-")) {
648 d.incomingDirName = file.Name()
649 }
650 }
651 }
652
653 d.incomingChecked = true
654 }
655
656 return d.incomingDirName != ""
657 }
658
659 // Object returns a fs.File pointing the object file, if exists
660 func (d *DotGit) Object(h plumbing.Hash) (billy.File, error) {
661 err := d.hasObject(h)
662 if err != nil {
663 return nil, err
664 }
665
666 obj1, err1 := d.fs.Open(d.objectPath(h))
667 if os.IsNotExist(err1) && d.hasIncomingObjects() {
668 obj2, err2 := d.fs.Open(d.incomingObjectPath(h))
669 if err2 != nil {
670 return obj1, err1
671 }
672 return obj2, err2
673 }
674 return obj1, err1
675 }
676
677 // ObjectStat returns a os.FileInfo pointing the object file, if exists
678 func (d *DotGit) ObjectStat(h plumbing.Hash) (os.FileInfo, error) {
679 err := d.hasObject(h)
680 if err != nil {
681 return nil, err
682 }
683
684 obj1, err1 := d.fs.Stat(d.objectPath(h))
685 if os.IsNotExist(err1) && d.hasIncomingObjects() {
686 obj2, err2 := d.fs.Stat(d.incomingObjectPath(h))
687 if err2 != nil {
688 return obj1, err1
689 }
690 return obj2, err2
691 }
692 return obj1, err1
693 }
694
695 // ObjectDelete removes the object file, if exists
696 func (d *DotGit) ObjectDelete(h plumbing.Hash) error {
697 d.cleanObjectList()
698
699 err1 := d.fs.Remove(d.objectPath(h))
700 if os.IsNotExist(err1) && d.hasIncomingObjects() {
701 err2 := d.fs.Remove(d.incomingObjectPath(h))
702 if err2 != nil {
703 return err1
704 }
705 return err2
706 }
707 return err1
708 }
709
710 func (d *DotGit) readReferenceFrom(rd io.Reader, name string) (ref *plumbing.Reference, err error) {
711 b, err := io.ReadAll(rd)
712 if err != nil {
713 return nil, err
714 }
715
716 if len(b) == 0 {
717 return nil, ErrEmptyRefFile
718 }
719
720 line := strings.TrimSpace(string(b))
721 return plumbing.NewReferenceFromStrings(name, line), nil
722 }
723
724 // checkReferenceAndTruncate reads the reference from the given file, or the `pack-refs` file if
725 // the file was empty. Then it checks that the old reference matches the stored reference and
726 // truncates the file.
727 func (d *DotGit) checkReferenceAndTruncate(f billy.File, old *plumbing.Reference) error {
728 if old == nil {
729 return nil
730 }
731
732 ref, err := d.readReferenceFrom(f, old.Name().String())
733 if errors.Is(err, ErrEmptyRefFile) {
734 // This may happen if the reference is being read from a newly created file.
735 // In that case, try getting the reference from the packed refs file.
736 ref, err = d.packedRef(old.Name())
737 }
738
739 if err != nil {
740 return err
741 }
742
743 if ref.Hash() != old.Hash() {
744 return storage.ErrReferenceHasChanged
745 }
746 _, err = f.Seek(0, io.SeekStart)
747 if err != nil {
748 return err
749 }
750 return f.Truncate(0)
751 }
752
753 func (d *DotGit) SetRef(r, old *plumbing.Reference) error {
754 if err := validReferenceName(r.Name()); err != nil {
755 return err
756 }
757
758 var content string
759 switch r.Type() {
760 case plumbing.SymbolicReference:
761 content = fmt.Sprintf("ref: %s\n", r.Target())
762 case plumbing.HashReference:
763 content = fmt.Sprintln(r.Hash().String())
764 }
765
766 fileName := r.Name().String()
767
768 return d.setRef(fileName, content, old)
769 }
770
771 // Refs scans the git directory collecting references, which it returns.
772 // Symbolic references are resolved and included in the output.
773 func (d *DotGit) Refs() ([]*plumbing.Reference, error) {
774 var refs []*plumbing.Reference
775 seen := make(map[plumbing.ReferenceName]bool)
776 if err := d.addRefFromHEAD(&refs); err != nil {
777 return nil, err
778 }
779
780 if err := d.addRefsFromRefDir(&refs, seen); err != nil {
781 return nil, err
782 }
783
784 if err := d.addRefsFromPackedRefs(&refs, seen); err != nil {
785 return nil, err
786 }
787
788 return refs, nil
789 }
790
791 // Ref returns the reference for a given reference name.
792 func (d *DotGit) Ref(name plumbing.ReferenceName) (*plumbing.Reference, error) {
793 if err := validReferenceName(name); err != nil {
794 return nil, err
795 }
796
797 ref, err := d.readReferenceFile(".", name.String())
798 if err == nil {
799 return ref, nil
800 }
801
802 return d.packedRef(name)
803 }
804
805 func (d *DotGit) findPackedRefsInFile(f billy.File, recv refsRecv) error {
806 s := bufio.NewScanner(f)
807 for s.Scan() {
808 ref, err := d.processLine(s.Text())
809 if err != nil {
810 return err
811 }
812
813 if !recv(ref) {
814 // skip parse
815 return nil
816 }
817 }
818 if err := s.Err(); err != nil {
819 return err
820 }
821 return nil
822 }
823
824 // refsRecv: returning true means that the reference continues to be resolved, otherwise it is stopped, which will speed up the lookup of a single reference.
825 type refsRecv func(*plumbing.Reference) bool
826
827 func (d *DotGit) findPackedRefs(recv refsRecv) error {
828 f, err := d.fs.Open(packedRefsPath)
829 if err != nil {
830 if os.IsNotExist(err) {
831 return nil
832 }
833 return err
834 }
835
836 defer ioutil.CheckClose(f, &err)
837 return d.findPackedRefsInFile(f, recv)
838 }
839
840 func (d *DotGit) packedRef(name plumbing.ReferenceName) (*plumbing.Reference, error) {
841 var ref *plumbing.Reference
842 if err := d.findPackedRefs(func(r *plumbing.Reference) bool {
843 if r != nil && r.Name() == name {
844 ref = r
845 // ref found
846 return false
847 }
848 return true
849 }); err != nil {
850 return nil, err
851 }
852 if ref != nil {
853 return ref, nil
854 }
855 return nil, plumbing.ErrReferenceNotFound
856 }
857
858 // RemoveRef removes a reference by name.
859 func (d *DotGit) RemoveRef(name plumbing.ReferenceName) error {
860 if err := validReferenceName(name); err != nil {
861 return err
862 }
863
864 path := d.fs.Join(".", name.String())
865 _, err := d.fs.Stat(path)
866 if err == nil {
867 err = d.fs.Remove(path)
868 // Drop down to remove it from the packed refs file, too.
869 }
870
871 if err != nil && !os.IsNotExist(err) {
872 return err
873 }
874
875 return d.rewritePackedRefsWithoutRef(name)
876 }
877
878 func refsRecvFunc(refs *[]*plumbing.Reference, seen map[plumbing.ReferenceName]bool) refsRecv {
879 return func(r *plumbing.Reference) bool {
880 if r != nil && !seen[r.Name()] {
881 *refs = append(*refs, r)
882 seen[r.Name()] = true
883 }
884 return true
885 }
886 }
887
888 func (d *DotGit) addRefsFromPackedRefs(refs *[]*plumbing.Reference, seen map[plumbing.ReferenceName]bool) (err error) {
889 return d.findPackedRefs(refsRecvFunc(refs, seen))
890 }
891
892 func (d *DotGit) addRefsFromPackedRefsFile(refs *[]*plumbing.Reference, f billy.File, seen map[plumbing.ReferenceName]bool) (err error) {
893 return d.findPackedRefsInFile(f, refsRecvFunc(refs, seen))
894 }
895
896 func (d *DotGit) openAndLockPackedRefs(doCreate bool) (
897 pr billy.File, err error,
898 ) {
899 var f billy.File
900 defer func() {
901 if err != nil && f != nil {
902 ioutil.CheckClose(f, &err)
903 }
904 }()
905
906 // File mode is retrieved from a constant defined in the target specific
907 // files (dotgit_rewrite_packed_refs_*). Some modes are not available
908 // in all filesystems.
909 openFlags := d.openAndLockPackedRefsMode()
910 if doCreate {
911 openFlags |= os.O_CREATE
912 }
913
914 // Keep trying to open and lock the file until we're sure the file
915 // didn't change between the open and the lock.
916 for {
917 f, err = d.fs.OpenFile(packedRefsPath, openFlags, 0600)
918 if err != nil {
919 if os.IsNotExist(err) && !doCreate {
920 return nil, nil
921 }
922
923 return nil, err
924 }
925 fi, err := d.fs.Stat(packedRefsPath)
926 if err != nil {
927 return nil, err
928 }
929 mtime := fi.ModTime()
930
931 err = f.Lock()
932 if err != nil {
933 return nil, err
934 }
935
936 fi, err = d.fs.Stat(packedRefsPath)
937 if err != nil {
938 return nil, err
939 }
940 if mtime.Equal(fi.ModTime()) {
941 break
942 }
943 // The file has changed since we opened it. Close and retry.
944 err = f.Close()
945 if err != nil {
946 return nil, err
947 }
948 }
949 return f, nil
950 }
951
952 func (d *DotGit) rewritePackedRefsWithoutRef(name plumbing.ReferenceName) (err error) {
953 pr, err := d.openAndLockPackedRefs(false)
954 if err != nil {
955 return err
956 }
957 if pr == nil {
958 return nil
959 }
960 defer ioutil.CheckClose(pr, &err)
961
962 // Creating the temp file in the same directory as the target file
963 // improves our chances for rename operation to be atomic.
964 tmp, err := d.fs.TempFile("", tmpPackedRefsPrefix)
965 if err != nil {
966 return err
967 }
968 tmpName := tmp.Name()
969 defer func() {
970 ioutil.CheckClose(tmp, &err)
971 _ = d.fs.Remove(tmpName) // don't check err, we might have renamed it
972 }()
973
974 s := bufio.NewScanner(pr)
975 found := false
976 for s.Scan() {
977 line := s.Text()
978 ref, err := d.processLine(line)
979 if err != nil {
980 return err
981 }
982
983 if ref != nil && ref.Name() == name {
984 found = true
985 continue
986 }
987
988 if _, err := fmt.Fprintln(tmp, line); err != nil {
989 return err
990 }
991 }
992
993 if err := s.Err(); err != nil {
994 return err
995 }
996
997 if !found {
998 return nil
999 }
1000
1001 return d.rewritePackedRefsWhileLocked(tmp, pr)
1002 }
1003
1004 // process lines from a packed-refs file
1005 func (d *DotGit) processLine(line string) (*plumbing.Reference, error) {
1006 if len(line) == 0 {
1007 return nil, nil
1008 }
1009
1010 switch line[0] {
1011 case '#': // comment - ignore
1012 return nil, nil
1013 case '^': // annotated tag commit of the previous line - ignore
1014 return nil, nil
1015 default:
1016 ws := strings.Split(line, " ") // hash then ref
1017 if len(ws) != 2 {
1018 return nil, ErrPackedRefsBadFormat
1019 }
1020
1021 return plumbing.NewReferenceFromStrings(ws[1], ws[0]), nil
1022 }
1023 }
1024
1025 func (d *DotGit) addRefsFromRefDir(refs *[]*plumbing.Reference, seen map[plumbing.ReferenceName]bool) error {
1026 return d.walkReferencesTree(refs, []string{refsPath}, seen)
1027 }
1028
1029 func (d *DotGit) walkReferencesTree(refs *[]*plumbing.Reference, relPath []string, seen map[plumbing.ReferenceName]bool) error {
1030 files, err := d.fs.ReadDir(d.fs.Join(relPath...))
1031 if err != nil {
1032 if os.IsNotExist(err) {
1033 // a race happened, and our directory is gone now
1034 return nil
1035 }
1036
1037 return err
1038 }
1039
1040 for _, f := range files {
1041 newRelPath := append(append([]string(nil), relPath...), f.Name())
1042 if f.IsDir() {
1043 if err = d.walkReferencesTree(refs, newRelPath, seen); err != nil {
1044 return err
1045 }
1046
1047 continue
1048 }
1049
1050 ref, err := d.readReferenceFile(".", strings.Join(newRelPath, "/"))
1051 if os.IsNotExist(err) {
1052 // a race happened, and our file is gone now
1053 continue
1054 }
1055 if err != nil {
1056 return err
1057 }
1058
1059 if ref != nil && !seen[ref.Name()] {
1060 *refs = append(*refs, ref)
1061 seen[ref.Name()] = true
1062 }
1063 }
1064
1065 return nil
1066 }
1067
1068 func (d *DotGit) addRefFromHEAD(refs *[]*plumbing.Reference) error {
1069 ref, err := d.readReferenceFile(".", "HEAD")
1070 if err != nil {
1071 if os.IsNotExist(err) {
1072 return nil
1073 }
1074
1075 return err
1076 }
1077
1078 *refs = append(*refs, ref)
1079 return nil
1080 }
1081
1082 func (d *DotGit) readReferenceFile(path, name string) (ref *plumbing.Reference, err error) {
1083 path = d.fs.Join(path, d.fs.Join(strings.Split(name, "/")...))
1084 st, err := d.fs.Stat(path)
1085 if err != nil {
1086 return nil, err
1087 }
1088 if st.IsDir() {
1089 return nil, ErrIsDir
1090 }
1091
1092 f, err := d.fs.Open(path)
1093 if err != nil {
1094 return nil, err
1095 }
1096 defer ioutil.CheckClose(f, &err)
1097
1098 return d.readReferenceFrom(f, name)
1099 }
1100
1101 func (d *DotGit) CountLooseRefs() (int, error) {
1102 var refs []*plumbing.Reference
1103 seen := make(map[plumbing.ReferenceName]bool)
1104 if err := d.addRefsFromRefDir(&refs, seen); err != nil {
1105 return 0, err
1106 }
1107
1108 return len(refs), nil
1109 }
1110
1111 // PackRefs packs all loose refs into the packed-refs file.
1112 //
1113 // This implementation only works under the assumption that the view
1114 // of the file system won't be updated during this operation. This
1115 // strategy would not work on a general file system though, without
1116 // locking each loose reference and checking it again before deleting
1117 // the file, because otherwise an updated reference could sneak in and
1118 // then be deleted by the packed-refs process. Alternatively, every
1119 // ref update could also lock packed-refs, so only one lock is
1120 // required during ref-packing. But that would worsen performance in
1121 // the common case.
1122 //
1123 // TODO: add an "all" boolean like the `git pack-refs --all` flag.
1124 // When `all` is false, it would only pack refs that have already been
1125 // packed, plus all tags.
1126 func (d *DotGit) PackRefs() (err error) {
1127 // Lock packed-refs, and create it if it doesn't exist yet.
1128 f, err := d.openAndLockPackedRefs(true)
1129 if err != nil {
1130 return err
1131 }
1132 defer ioutil.CheckClose(f, &err)
1133
1134 // Gather all refs using addRefsFromRefDir and addRefsFromPackedRefs.
1135 var refs []*plumbing.Reference
1136 seen := make(map[plumbing.ReferenceName]bool)
1137 if err = d.addRefsFromRefDir(&refs, seen); err != nil {
1138 return err
1139 }
1140 if len(refs) == 0 {
1141 // Nothing to do!
1142 return nil
1143 }
1144 numLooseRefs := len(refs)
1145 if err = d.addRefsFromPackedRefsFile(&refs, f, seen); err != nil {
1146 return err
1147 }
1148
1149 // Write them all to a new temp packed-refs file.
1150 tmp, err := d.fs.TempFile("", tmpPackedRefsPrefix)
1151 if err != nil {
1152 return err
1153 }
1154 tmpName := tmp.Name()
1155 defer func() {
1156 ioutil.CheckClose(tmp, &err)
1157 _ = d.fs.Remove(tmpName) // don't check err, we might have renamed it
1158 }()
1159
1160 w := bufio.NewWriter(tmp)
1161 for _, ref := range refs {
1162 _, err = w.WriteString(ref.String() + "\n")
1163 if err != nil {
1164 return err
1165 }
1166 }
1167 err = w.Flush()
1168 if err != nil {
1169 return err
1170 }
1171
1172 // Rename the temp packed-refs file.
1173 err = d.rewritePackedRefsWhileLocked(tmp, f)
1174 if err != nil {
1175 return err
1176 }
1177
1178 // Delete all the loose refs, while still holding the packed-refs
1179 // lock.
1180 for _, ref := range refs[:numLooseRefs] {
1181 path := d.fs.Join(".", ref.Name().String())
1182 err = d.fs.Remove(path)
1183 if err != nil && !os.IsNotExist(err) {
1184 return err
1185 }
1186 }
1187
1188 return nil
1189 }
1190
1191 // Module returns a billy.Filesystem pointing to the module folder.
1192 //
1193 // As a defence in depth against submodule name path traversal,
1194 // refuse names whose joined path leaves the modules/ subtree once
1195 // cleaned. The config-layer parser also validates submodule names,
1196 // but Module may be reached from any caller that constructs a
1197 // Submodule struct programmatically and so bypasses the parser.
1198 func (d *DotGit) Module(name string) (billy.Filesystem, error) {
1199 p := d.fs.Join(modulePath, name)
1200 cleaned := path.Clean(filepath.ToSlash(p))
1201 if cleaned != modulePath && !strings.HasPrefix(cleaned, modulePath+"/") {
1202 return nil, ErrModuleNameEscape
1203 }
1204 return d.fs.Chroot(p)
1205 }
1206
1207 func (d *DotGit) AddAlternate(remote string) error {
1208 altpath := d.fs.Join(objectsPath, infoPath, alternatesPath)
1209
1210 f, err := d.fs.OpenFile(altpath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)
1211 if err != nil {
1212 return fmt.Errorf("cannot open file: %w", err)
1213 }
1214 defer f.Close()
1215
1216 // locking in windows throws an error, based on comments
1217 // https://github.com/go-git/go-git/pull/860#issuecomment-1751823044
1218 // do not lock on windows platform.
1219 if runtime.GOOS != "windows" {
1220 if err = f.Lock(); err != nil {
1221 return fmt.Errorf("cannot lock file: %w", err)
1222 }
1223 defer f.Unlock()
1224 }
1225
1226 line := path.Join(remote, objectsPath) + "\n"
1227 _, err = io.WriteString(f, line)
1228 if err != nil {
1229 return fmt.Errorf("error writing 'alternates' file: %w", err)
1230 }
1231
1232 return nil
1233 }
1234
1235 // Alternates returns DotGit(s) based off paths in objects/info/alternates if
1236 // available. This can be used to checks if it's a shared repository.
1237 func (d *DotGit) Alternates() ([]*DotGit, error) {
1238 altpath := d.fs.Join(objectsPath, infoPath, alternatesPath)
1239 f, err := d.fs.Open(altpath)
1240 if err != nil {
1241 return nil, err
1242 }
1243 defer f.Close()
1244
1245 fs := d.options.AlternatesFS
1246 if fs == nil {
1247 fs = d.fs
1248 }
1249
1250 var alternates []*DotGit
1251 seen := make(map[string]struct{})
1252
1253 // Read alternate paths line-by-line and create DotGit objects.
1254 scanner := bufio.NewScanner(f)
1255 for scanner.Scan() {
1256 path := scanner.Text()
1257
1258 // Avoid creating multiple dotgits for the same alternative path.
1259 if _, ok := seen[path]; ok {
1260 continue
1261 }
1262
1263 seen[path] = struct{}{}
1264
1265 if filepath.IsAbs(path) {
1266 // Handling absolute paths should be straight-forward. However, the default osfs (Chroot)
1267 // tries to concatenate an abs path with the root path in some operations (e.g. Stat),
1268 // which leads to unexpected errors. Therefore, make the path relative to the current FS instead.
1269 if reflect.TypeOf(fs) == reflect.TypeOf(&chroot.ChrootHelper{}) {
1270 path, err = filepath.Rel(fs.Root(), path)
1271 if err != nil {
1272 return nil, fmt.Errorf("cannot make path %q relative: %w", path, err)
1273 }
1274 }
1275 } else {
1276 // By Git conventions, relative paths should be based on the object database (.git/objects/info)
1277 // location as per: https://www.kernel.org/pub/software/scm/git/docs/gitrepository-layout.html
1278 // However, due to the nature of go-git and its filesystem handling via Billy, paths cannot
1279 // cross its "chroot boundaries". Therefore, ignore any "../" and treat the path from the
1280 // fs root. If this is not correct based on the dotgit fs, set a different one via AlternatesFS.
1281 abs := filepath.Join(string(filepath.Separator), filepath.ToSlash(path))
1282 path = filepath.FromSlash(abs)
1283 }
1284
1285 // Aligns with upstream behavior: exit if target path is not a valid directory.
1286 if fi, err := fs.Stat(path); err != nil || !fi.IsDir() {
1287 return nil, fmt.Errorf("invalid object directory %q: %w", path, err)
1288 }
1289 afs, err := fs.Chroot(filepath.Dir(path))
1290 if err != nil {
1291 return nil, fmt.Errorf("cannot chroot %q: %w", path, err)
1292 }
1293 alternates = append(alternates, New(afs))
1294 }
1295
1296 if err = scanner.Err(); err != nil {
1297 return nil, err
1298 }
1299
1300 return alternates, nil
1301 }
1302
1303 // Fs returns the underlying filesystem of the DotGit folder.
1304 func (d *DotGit) Fs() billy.Filesystem {
1305 return d.fs
1306 }
1307
1308 func isHex(s string) bool {
1309 for _, b := range []byte(s) {
1310 if isNum(b) {
1311 continue
1312 }
1313 if isHexAlpha(b) {
1314 continue
1315 }
1316
1317 return false
1318 }
1319
1320 return true
1321 }
1322
1323 func isNum(b byte) bool {
1324 return b >= '0' && b <= '9'
1325 }
1326
1327 func isHexAlpha(b byte) bool {
1328 return b >= 'a' && b <= 'f' || b >= 'A' && b <= 'F'
1329 }
1330
1331 // incBytes increments a byte slice, which involves incrementing the
1332 // right-most byte, and following carry leftward.
1333 // It makes a copy so that the provided slice's underlying array is not modified.
1334 // If the overall operation overflows (e.g. incBytes(0xff, 0xff)), the second return parameter indicates that.
1335 func incBytes(in []byte) (out []byte, overflow bool) {
1336 out = make([]byte, len(in))
1337 copy(out, in)
1338 for i := len(out) - 1; i >= 0; i-- {
1339 out[i]++
1340 if out[i] != 0 {
1341 return // Didn't overflow.
1342 }
1343 }
1344 overflow = true
1345 return
1346 }