Debian Codegraph @

worktree.go

raw
1 package git
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10 "strings"
11
12 "github.com/go-git/go-billy/v5"
13 "github.com/go-git/go-billy/v5/util"
14
15 "github.com/go-git/go-git/v5/config"
16 "github.com/go-git/go-git/v5/plumbing"
17 "github.com/go-git/go-git/v5/plumbing/filemode"
18 "github.com/go-git/go-git/v5/plumbing/format/gitignore"
19 "github.com/go-git/go-git/v5/plumbing/format/index"
20 "github.com/go-git/go-git/v5/plumbing/object"
21 "github.com/go-git/go-git/v5/plumbing/storer"
22 "github.com/go-git/go-git/v5/utils/ioutil"
23 "github.com/go-git/go-git/v5/utils/merkletrie"
24 "github.com/go-git/go-git/v5/utils/sync"
25 )
26
27 var (
28 ErrWorktreeNotClean = errors.New("worktree is not clean")
29 ErrSubmoduleNotFound = errors.New("submodule not found")
30 ErrUnstagedChanges = errors.New("worktree contains unstaged changes")
31 ErrGitModulesSymlink = errors.New(gitmodulesFile + " is a symlink")
32 ErrNonFastForwardUpdate = errors.New("non-fast-forward update")
33 ErrRestoreWorktreeOnlyNotSupported = errors.New("worktree only is not supported")
34 )
35
36 // Worktree represents a git worktree.
37 type Worktree struct {
38 // Filesystem underlying filesystem.
39 Filesystem billy.Filesystem
40 // External excludes not found in the repository .gitignore
41 Excludes []gitignore.Pattern
42
43 r *Repository
44 }
45
46 // Pull incorporates changes from a remote repository into the current branch.
47 // Returns nil if the operation is successful, NoErrAlreadyUpToDate if there are
48 // no changes to be fetched, or an error.
49 //
50 // Pull only supports merges where the can be resolved as a fast-forward.
51 func (w *Worktree) Pull(o *PullOptions) error {
52 return w.PullContext(context.Background(), o)
53 }
54
55 // PullContext incorporates changes from a remote repository into the current
56 // branch. Returns nil if the operation is successful, NoErrAlreadyUpToDate if
57 // there are no changes to be fetched, or an error.
58 //
59 // Pull only supports merges where the can be resolved as a fast-forward.
60 //
61 // The provided Context must be non-nil. If the context expires before the
62 // operation is complete, an error is returned. The context only affects the
63 // transport operations.
64 func (w *Worktree) PullContext(ctx context.Context, o *PullOptions) error {
65 if err := o.Validate(); err != nil {
66 return err
67 }
68
69 remote, err := w.r.Remote(o.RemoteName)
70 if err != nil {
71 return err
72 }
73
74 fetchHead, err := remote.fetch(ctx, &FetchOptions{
75 RemoteName: o.RemoteName,
76 RemoteURL: o.RemoteURL,
77 Depth: o.Depth,
78 Auth: o.Auth,
79 Progress: o.Progress,
80 Force: o.Force,
81 InsecureSkipTLS: o.InsecureSkipTLS,
82 ClientCert: o.ClientCert,
83 ClientKey: o.ClientKey,
84 CABundle: o.CABundle,
85 ProxyOptions: o.ProxyOptions,
86 })
87
88 updated := true
89 if err == NoErrAlreadyUpToDate {
90 updated = false
91 } else if err != nil {
92 return err
93 }
94
95 ref, err := storer.ResolveReference(fetchHead, o.ReferenceName)
96 if err != nil {
97 return err
98 }
99
100 head, err := w.r.Head()
101 if err == nil {
102 // if we don't have a shallows list, just ignore it
103 shallowList, _ := w.r.Storer.Shallow()
104
105 var earliestShallow *plumbing.Hash
106 if len(shallowList) > 0 {
107 earliestShallow = &shallowList[0]
108 }
109
110 headAheadOfRef, err := isFastForward(w.r.Storer, ref.Hash(), head.Hash(), earliestShallow)
111 if err != nil {
112 return err
113 }
114
115 if !updated && headAheadOfRef {
116 return NoErrAlreadyUpToDate
117 }
118
119 ff, err := isFastForward(w.r.Storer, head.Hash(), ref.Hash(), earliestShallow)
120 if err != nil {
121 return err
122 }
123
124 if !ff {
125 return ErrNonFastForwardUpdate
126 }
127 }
128
129 if err != nil && err != plumbing.ErrReferenceNotFound {
130 return err
131 }
132
133 if err := w.updateHEAD(ref.Hash()); err != nil {
134 return err
135 }
136
137 if err := w.Reset(&ResetOptions{
138 Mode: MergeReset,
139 Commit: ref.Hash(),
140 }); err != nil {
141 return err
142 }
143
144 if o.RecurseSubmodules != NoRecurseSubmodules {
145 return w.updateSubmodules(ctx, &SubmoduleUpdateOptions{
146 RecurseSubmodules: o.RecurseSubmodules,
147 Auth: o.Auth,
148 })
149 }
150
151 return nil
152 }
153
154 func (w *Worktree) updateSubmodules(ctx context.Context, o *SubmoduleUpdateOptions) error {
155 s, err := w.Submodules()
156 if err != nil {
157 return err
158 }
159 o.Init = true
160 return s.UpdateContext(ctx, o)
161 }
162
163 // Checkout switch branches or restore working tree files.
164 func (w *Worktree) Checkout(opts *CheckoutOptions) error {
165 if err := opts.Validate(); err != nil {
166 return err
167 }
168
169 if opts.Create {
170 if err := w.createBranch(opts); err != nil {
171 return err
172 }
173 }
174
175 c, err := w.getCommitFromCheckoutOptions(opts)
176 if err != nil {
177 return err
178 }
179
180 ro := &ResetOptions{Commit: c, Mode: MergeReset}
181 if opts.Force {
182 ro.Mode = HardReset
183 } else if opts.Keep {
184 ro.Mode = SoftReset
185 }
186
187 if !opts.Hash.IsZero() && !opts.Create {
188 err = w.setHEADToCommit(opts.Hash)
189 } else {
190 err = w.setHEADToBranch(opts.Branch, c)
191 }
192
193 if err != nil {
194 return err
195 }
196
197 if len(opts.SparseCheckoutDirectories) > 0 {
198 return w.ResetSparsely(ro, opts.SparseCheckoutDirectories)
199 }
200
201 return w.Reset(ro)
202 }
203
204 func (w *Worktree) createBranch(opts *CheckoutOptions) error {
205 if err := opts.Branch.Validate(); err != nil {
206 return err
207 }
208
209 _, err := w.r.Storer.Reference(opts.Branch)
210 if err == nil {
211 return fmt.Errorf("a branch named %q already exists", opts.Branch)
212 }
213
214 if err != plumbing.ErrReferenceNotFound {
215 return err
216 }
217
218 if opts.Hash.IsZero() {
219 ref, err := w.r.Head()
220 if err != nil {
221 return err
222 }
223
224 opts.Hash = ref.Hash()
225 }
226
227 return w.r.Storer.SetReference(
228 plumbing.NewHashReference(opts.Branch, opts.Hash),
229 )
230 }
231
232 func (w *Worktree) getCommitFromCheckoutOptions(opts *CheckoutOptions) (plumbing.Hash, error) {
233 hash := opts.Hash
234 if hash.IsZero() {
235 b, err := w.r.Reference(opts.Branch, true)
236 if err != nil {
237 return plumbing.ZeroHash, err
238 }
239
240 hash = b.Hash()
241 }
242
243 o, err := w.r.Object(plumbing.AnyObject, hash)
244 if err != nil {
245 return plumbing.ZeroHash, err
246 }
247
248 switch o := o.(type) {
249 case *object.Tag:
250 if o.TargetType != plumbing.CommitObject {
251 return plumbing.ZeroHash, fmt.Errorf("%w: tag target %q", object.ErrUnsupportedObject, o.TargetType)
252 }
253
254 return o.Target, nil
255 case *object.Commit:
256 return o.Hash, nil
257 }
258
259 return plumbing.ZeroHash, fmt.Errorf("%w: %q", object.ErrUnsupportedObject, o.Type())
260 }
261
262 func (w *Worktree) setHEADToCommit(commit plumbing.Hash) error {
263 head := plumbing.NewHashReference(plumbing.HEAD, commit)
264 return w.r.Storer.SetReference(head)
265 }
266
267 func (w *Worktree) setHEADToBranch(branch plumbing.ReferenceName, commit plumbing.Hash) error {
268 target, err := w.r.Storer.Reference(branch)
269 if err != nil {
270 return err
271 }
272
273 var head *plumbing.Reference
274 if target.Name().IsBranch() {
275 head = plumbing.NewSymbolicReference(plumbing.HEAD, target.Name())
276 } else {
277 head = plumbing.NewHashReference(plumbing.HEAD, commit)
278 }
279
280 return w.r.Storer.SetReference(head)
281 }
282
283 func (w *Worktree) ResetSparsely(opts *ResetOptions, dirs []string) error {
284 if err := opts.Validate(w.r); err != nil {
285 return err
286 }
287
288 if opts.Mode == MergeReset {
289 unstaged, err := w.containsUnstagedChanges()
290 if err != nil {
291 return err
292 }
293
294 if unstaged {
295 return ErrUnstagedChanges
296 }
297 }
298
299 if err := w.setHEADCommit(opts.Commit); err != nil {
300 return err
301 }
302
303 if opts.Mode == SoftReset {
304 return nil
305 }
306
307 t, err := w.r.getTreeFromCommitHash(opts.Commit)
308 if err != nil {
309 return err
310 }
311
312 var removedFiles []string
313 if opts.Mode == MixedReset || opts.Mode == MergeReset || opts.Mode == HardReset {
314 if removedFiles, err = w.resetIndex(t, dirs, opts.Files); err != nil {
315 return err
316 }
317 }
318
319 if opts.Mode == MergeReset && len(removedFiles) > 0 {
320 if err := w.resetWorktree(t, removedFiles); err != nil {
321 return err
322 }
323 }
324
325 if opts.Mode == HardReset {
326 if err := w.resetWorktree(t, opts.Files); err != nil {
327 return err
328 }
329 }
330
331 return nil
332 }
333
334 // Restore restores specified files in the working tree or stage with contents from
335 // a restore source. If a path is tracked but does not exist in the restore,
336 // source, it will be removed to match the source.
337 //
338 // If Staged and Worktree are true, then the restore source will be the index.
339 // If only Staged is true, then the restore source will be HEAD.
340 // If only Worktree is true or neither Staged nor Worktree are true, will
341 // result in ErrRestoreWorktreeOnlyNotSupported because restoring the working
342 // tree while leaving the stage untouched is not currently supported.
343 //
344 // Restore with no files specified will return ErrNoRestorePaths.
345 func (w *Worktree) Restore(o *RestoreOptions) error {
346 if err := o.Validate(); err != nil {
347 return err
348 }
349
350 if o.Staged {
351 opts := &ResetOptions{
352 Files: o.Files,
353 }
354
355 if o.Worktree {
356 // If we are doing both Worktree and Staging then it is a hard reset
357 opts.Mode = HardReset
358 } else {
359 // If we are doing just staging then it is a mixed reset
360 opts.Mode = MixedReset
361 }
362
363 return w.Reset(opts)
364 }
365
366 return ErrRestoreWorktreeOnlyNotSupported
367 }
368
369 // Reset the worktree to a specified state.
370 func (w *Worktree) Reset(opts *ResetOptions) error {
371 return w.ResetSparsely(opts, nil)
372 }
373
374 func (w *Worktree) resetIndex(t *object.Tree, dirs []string, files []string) ([]string, error) {
375 idx, err := w.r.Storer.Index()
376 if err != nil {
377 return nil, err
378 }
379
380 b := newIndexBuilder(idx)
381
382 changes, err := w.diffTreeWithStaging(t, true)
383 if err != nil {
384 return nil, err
385 }
386
387 removedFiles := make([]string, 0, len(changes))
388 filesMap := buildFilePathMap(files)
389 for _, ch := range changes {
390 a, err := ch.Action()
391 if err != nil {
392 return nil, err
393 }
394
395 var name string
396 var e *object.TreeEntry
397
398 switch a {
399 case merkletrie.Modify, merkletrie.Insert:
400 name = ch.To.String()
401 e, err = t.FindEntry(name)
402 if err != nil {
403 return nil, err
404 }
405 case merkletrie.Delete:
406 name = ch.From.String()
407 }
408
409 if len(files) > 0 {
410 contains := inFiles(filesMap, name)
411 if !contains {
412 continue
413 }
414 }
415
416 b.Remove(name)
417 removedFiles = append(removedFiles, name)
418 if e == nil {
419 continue
420 }
421
422 b.Add(&index.Entry{
423 Name: name,
424 Hash: e.Hash,
425 Mode: e.Mode,
426 })
427
428 }
429
430 b.Write(idx)
431
432 if len(dirs) > 0 {
433 idx.SkipUnless(dirs)
434 }
435
436 return removedFiles, w.r.Storer.SetIndex(idx)
437 }
438
439 // inFiles checks if the given file is in the list of files. The incoming filepaths in files should be cleaned before calling this function.
440 func inFiles(files map[string]struct{}, v string) bool {
441 v = filepath.Clean(v)
442 _, exists := files[v]
443 return exists
444 }
445
446 func (w *Worktree) resetWorktree(t *object.Tree, files []string) error {
447 changes, err := w.diffStagingWithWorktree(true, false)
448 if err != nil {
449 return err
450 }
451
452 idx, err := w.r.Storer.Index()
453 if err != nil {
454 return err
455 }
456 b := newIndexBuilder(idx)
457
458 filesMap := buildFilePathMap(files)
459 for _, ch := range changes {
460 if len(files) > 0 {
461 file := ""
462 if ch.From != nil {
463 file = ch.From.String()
464 } else if ch.To != nil {
465 file = ch.To.String()
466 }
467
468 if file == "" {
469 continue
470 }
471
472 contains := inFiles(filesMap, file)
473 if !contains {
474 continue
475 }
476 }
477
478 if err := w.checkoutChange(ch, t, b); err != nil {
479 return err
480 }
481 }
482
483 b.Write(idx)
484 return w.r.Storer.SetIndex(idx)
485 }
486
487 func (w *Worktree) checkoutChange(ch merkletrie.Change, t *object.Tree, idx *indexBuilder) error {
488 a, err := ch.Action()
489 if err != nil {
490 return err
491 }
492
493 var e *object.TreeEntry
494 var name string
495 var isSubmodule bool
496
497 switch a {
498 case merkletrie.Modify, merkletrie.Insert:
499 name = ch.To.String()
500 e, err = t.FindEntry(name)
501 if err != nil {
502 return err
503 }
504
505 isSubmodule = e.Mode == filemode.Submodule
506 case merkletrie.Delete:
507 return rmFileAndDirsIfEmpty(w.Filesystem, ch.From.String())
508 }
509
510 if isSubmodule {
511 return w.checkoutChangeSubmodule(name, a, e, idx)
512 }
513
514 return w.checkoutChangeRegularFile(name, a, t, e, idx)
515 }
516
517 func (w *Worktree) containsUnstagedChanges() (bool, error) {
518 ch, err := w.diffStagingWithWorktree(false, true)
519 if err != nil {
520 return false, err
521 }
522
523 for _, c := range ch {
524 a, err := c.Action()
525 if err != nil {
526 return false, err
527 }
528
529 if a == merkletrie.Insert {
530 continue
531 }
532
533 return true, nil
534 }
535
536 return false, nil
537 }
538
539 func (w *Worktree) setHEADCommit(commit plumbing.Hash) error {
540 head, err := w.r.Reference(plumbing.HEAD, false)
541 if err != nil {
542 return err
543 }
544
545 if head.Type() == plumbing.HashReference {
546 head = plumbing.NewHashReference(plumbing.HEAD, commit)
547 return w.r.Storer.SetReference(head)
548 }
549
550 branch, err := w.r.Reference(head.Target(), false)
551 if err != nil {
552 return err
553 }
554
555 if !branch.Name().IsBranch() {
556 return fmt.Errorf("invalid HEAD target should be a branch, found %s", branch.Type())
557 }
558
559 branch = plumbing.NewHashReference(branch.Name(), commit)
560 return w.r.Storer.SetReference(branch)
561 }
562
563 func (w *Worktree) checkoutChangeSubmodule(name string,
564 a merkletrie.Action,
565 e *object.TreeEntry,
566 idx *indexBuilder,
567 ) error {
568 switch a {
569 case merkletrie.Modify:
570 sub, err := w.Submodule(name)
571 if err != nil {
572 return err
573 }
574
575 if !sub.initialized {
576 return nil
577 }
578
579 return w.addIndexFromTreeEntry(name, e, idx)
580 case merkletrie.Insert:
581 mode, err := e.Mode.ToOSFileMode()
582 if err != nil {
583 return err
584 }
585
586 if err := w.clearBlockingSymlinks(name); err != nil {
587 return err
588 }
589
590 if err := w.Filesystem.MkdirAll(name, mode); err != nil {
591 return err
592 }
593
594 return w.addIndexFromTreeEntry(name, e, idx)
595 }
596
597 return nil
598 }
599
600 func (w *Worktree) checkoutChangeRegularFile(name string,
601 a merkletrie.Action,
602 t *object.Tree,
603 e *object.TreeEntry,
604 idx *indexBuilder,
605 ) error {
606 switch a {
607 case merkletrie.Modify:
608 idx.Remove(name)
609
610 // to apply perm changes the file is deleted, billy doesn't implement
611 // chmod
612 if err := w.Filesystem.Remove(name); err != nil {
613 return err
614 }
615
616 fallthrough
617 case merkletrie.Insert:
618 f, err := t.File(name)
619 if err != nil {
620 return err
621 }
622
623 if err := w.checkoutFile(f); err != nil {
624 return err
625 }
626
627 return w.addIndexFromFile(name, e.Hash, f.Mode, idx)
628 }
629
630 return nil
631 }
632
633 // clearBlockingSymlinks removes a symlink that is in the way of
634 // materialising name, so the checkout writes a real entry in its place
635 // instead of following the link out of the worktree. Two cases:
636 //
637 // - a leading directory component that is a symlink (e.g. "s" while
638 // writing "s/config", where "s" links to ".git"): OpenFile/MkdirAll
639 // would traverse it, so the write would land under the link's target.
640 // - the final component itself being a symlink (e.g. writing "s" while
641 // "s" links to ".git/config"): OpenFile with O_TRUNC, or Symlink,
642 // would follow/replace through it and clobber the target.
643 //
644 // A symlink can never be a legitimate parent of, or the destination for,
645 // a tracked entry, so removing it is always correct. This mirrors upstream
646 // Git's forced checkout, which unlinks a blocking symlink in the leading
647 // path (create_directories) and unlinks an existing entry before
648 // write_entry.
649 // https://github.com/git/git/blob/v2.54.0/entry.c#L50
650 func (w *Worktree) clearBlockingSymlinks(name string) error {
651 var dirs []string
652 for dir := filepath.Dir(name); dir != "." && dir != "" && dir != string(filepath.Separator); dir = filepath.Dir(dir) {
653 dirs = append(dirs, dir)
654 }
655 // Leading components, shallowest-first: removing the shallowest symlink
656 // invalidates every component beneath it, so a single removal is enough.
657 for i := len(dirs) - 1; i >= 0; i-- {
658 fi, err := w.Filesystem.Lstat(dirs[i])
659 if err != nil {
660 // A missing component is created as a real directory by the
661 // checkout. Any other error means we cannot tell whether it is
662 // a symlink, so surface it instead of leaving a blocking link in
663 // place and failing later in a harder-to-diagnose way.
664 if os.IsNotExist(err) {
665 continue
666 }
667 return err
668 }
669 if fi.Mode()&os.ModeSymlink != 0 {
670 return w.Filesystem.Remove(dirs[i])
671 }
672 }
673 // Final component: an existing symlink here would be followed by the
674 // subsequent OpenFile/Symlink/MkdirAll, so replace it.
675 fi, err := w.Filesystem.Lstat(name)
676 if err != nil {
677 if os.IsNotExist(err) {
678 return nil
679 }
680 return err
681 }
682 if fi.Mode()&os.ModeSymlink != 0 {
683 return w.Filesystem.Remove(name)
684 }
685 return nil
686 }
687
688 func (w *Worktree) checkoutFile(f *object.File) (err error) {
689 // checkoutFile is the materialisation boundary for tracked entries.
690 // Remove any blocking symlink first so the subsequent OpenFile or
691 // Symlink call writes the entry itself instead of following a planted
692 // final-component link in the underlying filesystem.
693 if err := w.clearBlockingSymlinks(f.Name); err != nil {
694 return err
695 }
696
697 mode, err := f.Mode.ToOSFileMode()
698 if err != nil {
699 return
700 }
701
702 if mode&os.ModeSymlink != 0 {
703 return w.checkoutFileSymlink(f)
704 }
705
706 from, err := f.Reader()
707 if err != nil {
708 return
709 }
710
711 defer ioutil.CheckClose(from, &err)
712
713 to, err := w.Filesystem.OpenFile(f.Name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode.Perm())
714 if err != nil {
715 return
716 }
717
718 defer ioutil.CheckClose(to, &err)
719 buf := sync.GetByteSlice()
720 _, err = io.CopyBuffer(to, from, *buf)
721 sync.PutByteSlice(buf)
722 return
723 }
724
725 func (w *Worktree) checkoutFileSymlink(f *object.File) (err error) {
726 // .gitmodules symlink rejection (and its NTFS / HFS variants) is
727 // enforced by the worktreeFilesystem wrapper's Symlink method via
728 // validSymlinkName. See https://github.com/git/git/commit/10ecfa7
729 // for the upstream rationale.
730
731 from, err := f.Reader()
732 if err != nil {
733 return
734 }
735
736 defer ioutil.CheckClose(from, &err)
737
738 bytes, err := io.ReadAll(from)
739 if err != nil {
740 return
741 }
742
743 err = w.Filesystem.Symlink(string(bytes), f.Name)
744
745 // On windows, this might fail.
746 // Follow Git on Windows behavior by writing the link as it is.
747 if err != nil && isSymlinkWindowsNonAdmin(err) {
748 mode, _ := f.Mode.ToOSFileMode()
749
750 to, err := w.Filesystem.OpenFile(f.Name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode.Perm())
751 if err != nil {
752 return err
753 }
754
755 defer ioutil.CheckClose(to, &err)
756
757 _, err = to.Write(bytes)
758 return err
759 }
760 return
761 }
762
763 func (w *Worktree) addIndexFromTreeEntry(name string, f *object.TreeEntry, idx *indexBuilder) error {
764 idx.Remove(name)
765 idx.Add(&index.Entry{
766 Hash: f.Hash,
767 Name: name,
768 Mode: filemode.Submodule,
769 })
770 return nil
771 }
772
773 func (w *Worktree) addIndexFromFile(name string, h plumbing.Hash, mode filemode.FileMode, idx *indexBuilder) error {
774 idx.Remove(name)
775 fi, err := w.Filesystem.Lstat(name)
776 if err != nil {
777 return err
778 }
779
780 e := &index.Entry{
781 Hash: h,
782 Name: name,
783 Mode: mode,
784 ModifiedAt: fi.ModTime(),
785 Size: uint32(fi.Size()),
786 }
787
788 // if the FileInfo.Sys() comes from os the ctime, dev, inode, uid and gid
789 // can be retrieved, otherwise this doesn't apply
790 if fillSystemInfo != nil {
791 fillSystemInfo(e, fi.Sys())
792 }
793 idx.Add(e)
794 return nil
795 }
796
797 func (r *Repository) getTreeFromCommitHash(commit plumbing.Hash) (*object.Tree, error) {
798 c, err := r.CommitObject(commit)
799 if err != nil {
800 return nil, err
801 }
802
803 return c.Tree()
804 }
805
806 var fillSystemInfo func(e *index.Entry, sys interface{})
807
808 const gitmodulesFile = ".gitmodules"
809
810 // Submodule returns the submodule with the given name
811 func (w *Worktree) Submodule(name string) (*Submodule, error) {
812 l, err := w.Submodules()
813 if err != nil {
814 return nil, err
815 }
816
817 for _, m := range l {
818 if m.Config().Name == name {
819 return m, nil
820 }
821 }
822
823 return nil, ErrSubmoduleNotFound
824 }
825
826 // Submodules returns all the available submodules
827 func (w *Worktree) Submodules() (Submodules, error) {
828 l := make(Submodules, 0)
829 m, err := w.readGitmodulesFile()
830 if err != nil || m == nil {
831 return l, err
832 }
833
834 c, err := w.r.Config()
835 if err != nil {
836 return nil, err
837 }
838
839 for _, s := range m.Submodules {
840 l = append(l, w.newSubmodule(s, c.Submodules[s.Name]))
841 }
842
843 return l, nil
844 }
845
846 func (w *Worktree) newSubmodule(fromModules, fromConfig *config.Submodule) *Submodule {
847 m := &Submodule{w: w}
848 m.initialized = fromConfig != nil
849
850 if !m.initialized {
851 m.c = fromModules
852 return m
853 }
854
855 m.c = fromConfig
856 m.c.Path = fromModules.Path
857 return m
858 }
859
860 func (w *Worktree) isSymlink(path string) bool {
861 if s, err := w.Filesystem.Lstat(path); err == nil {
862 return s.Mode()&os.ModeSymlink != 0
863 }
864 return false
865 }
866
867 func (w *Worktree) readGitmodulesFile() (*config.Modules, error) {
868 if w.isSymlink(gitmodulesFile) {
869 return nil, ErrGitModulesSymlink
870 }
871
872 f, err := w.Filesystem.Open(gitmodulesFile)
873 if err != nil {
874 if os.IsNotExist(err) {
875 return nil, nil
876 }
877
878 return nil, err
879 }
880
881 defer f.Close()
882 input, err := io.ReadAll(f)
883 if err != nil {
884 return nil, err
885 }
886
887 m := config.NewModules()
888 if err := m.Unmarshal(input); err != nil {
889 return m, err
890 }
891
892 return m, nil
893 }
894
895 // Clean the worktree by removing untracked files.
896 // An empty dir could be removed - this is what `git clean -f -d .` does.
897 func (w *Worktree) Clean(opts *CleanOptions) error {
898 s, err := w.Status()
899 if err != nil {
900 return err
901 }
902
903 root := ""
904 files, err := w.Filesystem.ReadDir(root)
905 if err != nil {
906 return err
907 }
908 return w.doClean(s, opts, root, files)
909 }
910
911 func (w *Worktree) doClean(status Status, opts *CleanOptions, dir string, files []os.FileInfo) error {
912 for _, fi := range files {
913 if fi.Name() == GitDirName {
914 continue
915 }
916
917 // relative path under the root
918 path := filepath.Join(dir, fi.Name())
919 if fi.IsDir() {
920 if !opts.Dir {
921 continue
922 }
923
924 subfiles, err := w.Filesystem.ReadDir(path)
925 if err != nil {
926 return err
927 }
928 err = w.doClean(status, opts, path, subfiles)
929 if err != nil {
930 return err
931 }
932 } else {
933 if status.IsUntracked(path) {
934 if err := w.Filesystem.Remove(path); err != nil {
935 return err
936 }
937 }
938 }
939 }
940
941 if opts.Dir && dir != "" {
942 _, err := removeDirIfEmpty(w.Filesystem, dir)
943 return err
944 }
945
946 return nil
947 }
948
949 // GrepResult is structure of a grep result.
950 type GrepResult struct {
951 // FileName is the name of file which contains match.
952 FileName string
953 // LineNumber is the line number of a file at which a match was found.
954 LineNumber int
955 // Content is the content of the file at the matching line.
956 Content string
957 // TreeName is the name of the tree (reference name/commit hash) at
958 // which the match was performed.
959 TreeName string
960 }
961
962 func (gr GrepResult) String() string {
963 return fmt.Sprintf("%s:%s:%d:%s", gr.TreeName, gr.FileName, gr.LineNumber, gr.Content)
964 }
965
966 // Grep performs grep on a repository.
967 func (r *Repository) Grep(opts *GrepOptions) ([]GrepResult, error) {
968 if err := opts.validate(r); err != nil {
969 return nil, err
970 }
971
972 // Obtain commit hash from options (CommitHash or ReferenceName).
973 var commitHash plumbing.Hash
974 // treeName contains the value of TreeName in GrepResult.
975 var treeName string
976
977 if opts.ReferenceName != "" {
978 ref, err := r.Reference(opts.ReferenceName, true)
979 if err != nil {
980 return nil, err
981 }
982 commitHash = ref.Hash()
983 treeName = opts.ReferenceName.String()
984 } else if !opts.CommitHash.IsZero() {
985 commitHash = opts.CommitHash
986 treeName = opts.CommitHash.String()
987 }
988
989 // Obtain a tree from the commit hash and get a tracked files iterator from
990 // the tree.
991 tree, err := r.getTreeFromCommitHash(commitHash)
992 if err != nil {
993 return nil, err
994 }
995 fileiter := tree.Files()
996
997 return findMatchInFiles(fileiter, treeName, opts)
998 }
999
1000 // Grep performs grep on a worktree.
1001 func (w *Worktree) Grep(opts *GrepOptions) ([]GrepResult, error) {
1002 return w.r.Grep(opts)
1003 }
1004
1005 // findMatchInFiles takes a FileIter, worktree name and GrepOptions, and
1006 // returns a slice of GrepResult containing the result of regex pattern matching
1007 // in content of all the files.
1008 func findMatchInFiles(fileiter *object.FileIter, treeName string, opts *GrepOptions) ([]GrepResult, error) {
1009 var results []GrepResult
1010
1011 err := fileiter.ForEach(func(file *object.File) error {
1012 var fileInPathSpec bool
1013
1014 // When no pathspecs are provided, search all the files.
1015 if len(opts.PathSpecs) == 0 {
1016 fileInPathSpec = true
1017 }
1018
1019 // Check if the file name matches with the pathspec. Break out of the
1020 // loop once a match is found.
1021 for _, pathSpec := range opts.PathSpecs {
1022 if pathSpec != nil && pathSpec.MatchString(file.Name) {
1023 fileInPathSpec = true
1024 break
1025 }
1026 }
1027
1028 // If the file does not match with any of the pathspec, skip it.
1029 if !fileInPathSpec {
1030 return nil
1031 }
1032
1033 grepResults, err := findMatchInFile(file, treeName, opts)
1034 if err != nil {
1035 return err
1036 }
1037 results = append(results, grepResults...)
1038
1039 return nil
1040 })
1041
1042 return results, err
1043 }
1044
1045 // findMatchInFile takes a single File, worktree name and GrepOptions,
1046 // and returns a slice of GrepResult containing the result of regex pattern
1047 // matching in the given file.
1048 func findMatchInFile(file *object.File, treeName string, opts *GrepOptions) ([]GrepResult, error) {
1049 var grepResults []GrepResult
1050
1051 content, err := file.Contents()
1052 if err != nil {
1053 return grepResults, err
1054 }
1055
1056 // Split the file content and parse line-by-line.
1057 contentByLine := strings.Split(content, "\n")
1058 for lineNum, cnt := range contentByLine {
1059 addToResult := false
1060
1061 // Match the patterns and content. Break out of the loop once a
1062 // match is found.
1063 for _, pattern := range opts.Patterns {
1064 if pattern != nil && pattern.MatchString(cnt) {
1065 // Add to result only if invert match is not enabled.
1066 if !opts.InvertMatch {
1067 addToResult = true
1068 break
1069 }
1070 } else if opts.InvertMatch {
1071 // If matching fails, and invert match is enabled, add to
1072 // results.
1073 addToResult = true
1074 break
1075 }
1076 }
1077
1078 if addToResult {
1079 grepResults = append(grepResults, GrepResult{
1080 FileName: file.Name,
1081 LineNumber: lineNum + 1,
1082 Content: cnt,
1083 TreeName: treeName,
1084 })
1085 }
1086 }
1087
1088 return grepResults, nil
1089 }
1090
1091 // will walk up the directory tree removing all encountered empty
1092 // directories, not just the one containing this file
1093 func rmFileAndDirsIfEmpty(fs billy.Filesystem, name string) error {
1094 if err := util.RemoveAll(fs, name); err != nil {
1095 return err
1096 }
1097
1098 dir := filepath.Dir(name)
1099 for {
1100 removed, err := removeDirIfEmpty(fs, dir)
1101 if err != nil && !os.IsNotExist(err) {
1102 return err
1103 }
1104
1105 if !removed {
1106 // directory was not empty and not removed,
1107 // stop checking parents
1108 break
1109 }
1110
1111 // move to parent directory
1112 dir = filepath.Dir(dir)
1113 }
1114
1115 return nil
1116 }
1117
1118 // removeDirIfEmpty will remove the supplied directory `dir` if
1119 // `dir` is empty
1120 // returns true if the directory was removed
1121 func removeDirIfEmpty(fs billy.Filesystem, dir string) (bool, error) {
1122 files, err := fs.ReadDir(dir)
1123 if err != nil {
1124 return false, err
1125 }
1126
1127 if len(files) > 0 {
1128 return false, nil
1129 }
1130
1131 err = fs.Remove(dir)
1132 if err != nil {
1133 return false, err
1134 }
1135
1136 return true, nil
1137 }
1138
1139 type indexBuilder struct {
1140 entries map[string]*index.Entry
1141 }
1142
1143 func newIndexBuilder(idx *index.Index) *indexBuilder {
1144 entries := make(map[string]*index.Entry, len(idx.Entries))
1145 for _, e := range idx.Entries {
1146 entries[e.Name] = e
1147 }
1148 return &indexBuilder{
1149 entries: entries,
1150 }
1151 }
1152
1153 func (b *indexBuilder) Write(idx *index.Index) {
1154 idx.Entries = idx.Entries[:0]
1155 for _, e := range b.entries {
1156 idx.Entries = append(idx.Entries, e)
1157 }
1158 }
1159
1160 func (b *indexBuilder) Add(e *index.Entry) {
1161 b.entries[e.Name] = e
1162 }
1163
1164 func (b *indexBuilder) Remove(name string) {
1165 delete(b.entries, filepath.ToSlash(name))
1166 }
1167
1168 // buildFilePathMap creates a map of cleaned file paths for efficient lookup.
1169 // Returns nil if the input slice is empty.
1170 func buildFilePathMap(files []string) map[string]struct{} {
1171 if len(files) == 0 {
1172 return nil
1173 }
1174 filesMap := make(map[string]struct{}, len(files))
1175 for _, f := range files {
1176 filesMap[filepath.Clean(f)] = struct{}{}
1177 }
1178 return filesMap
1179 }