forked from go-git/go-git
-
Notifications
You must be signed in to change notification settings - Fork 1
/
worktree.go
1195 lines (985 loc) · 26.6 KB
/
worktree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package git
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/util"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/filemode"
"github.com/go-git/go-git/v5/plumbing/format/gitignore"
"github.com/go-git/go-git/v5/plumbing/format/index"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/storer"
"github.com/go-git/go-git/v5/utils/ioutil"
"github.com/go-git/go-git/v5/utils/merkletrie"
"github.com/go-git/go-git/v5/utils/sync"
)
var (
ErrWorktreeNotClean = errors.New("worktree is not clean")
ErrSubmoduleNotFound = errors.New("submodule not found")
ErrUnstagedChanges = errors.New("worktree contains unstaged changes")
ErrGitModulesSymlink = errors.New(gitmodulesFile + " is a symlink")
ErrNonFastForwardUpdate = errors.New("non-fast-forward update")
ErrRestoreWorktreeOnlyNotSupported = errors.New("worktree only is not supported")
)
// Worktree represents a git worktree.
type Worktree struct {
// Filesystem underlying filesystem.
Filesystem billy.Filesystem
// External excludes not found in the repository .gitignore
Excludes []gitignore.Pattern
r *Repository
}
// Pull incorporates changes from a remote repository into the current branch.
// Returns nil if the operation is successful, NoErrAlreadyUpToDate if there are
// no changes to be fetched, or an error.
//
// Pull only supports merges where the can be resolved as a fast-forward.
func (w *Worktree) Pull(o *PullOptions) error {
return w.PullContext(context.Background(), o)
}
// PullContext incorporates changes from a remote repository into the current
// branch. Returns nil if the operation is successful, NoErrAlreadyUpToDate if
// there are no changes to be fetched, or an error.
//
// Pull only supports merges where the can be resolved as a fast-forward.
//
// The provided Context must be non-nil. If the context expires before the
// operation is complete, an error is returned. The context only affects the
// transport operations.
func (w *Worktree) PullContext(ctx context.Context, o *PullOptions) error {
if err := o.Validate(); err != nil {
return err
}
remote, err := w.r.Remote(o.RemoteName)
if err != nil {
return err
}
fetchHead, err := remote.fetch(ctx, &FetchOptions{
RemoteName: o.RemoteName,
RemoteURL: o.RemoteURL,
Depth: o.Depth,
Auth: o.Auth,
Progress: o.Progress,
Force: o.Force,
InsecureSkipTLS: o.InsecureSkipTLS,
CABundle: o.CABundle,
ProxyOptions: o.ProxyOptions,
})
updated := true
if err == NoErrAlreadyUpToDate {
updated = false
} else if err != nil {
return err
}
ref, err := storer.ResolveReference(fetchHead, o.ReferenceName)
if err != nil {
return err
}
head, err := w.r.Head()
if err == nil {
// if we don't have a shallows list, just ignore it
shallowList, _ := w.r.Storer.Shallow()
var earliestShallow *plumbing.Hash
if len(shallowList) > 0 {
earliestShallow = &shallowList[0]
}
headAheadOfRef, err := isFastForward(w.r.Storer, ref.Hash(), head.Hash(), earliestShallow)
if err != nil {
return err
}
if !updated && headAheadOfRef {
return NoErrAlreadyUpToDate
}
ff, err := isFastForward(w.r.Storer, head.Hash(), ref.Hash(), earliestShallow)
if err != nil {
return err
}
if !ff {
return ErrNonFastForwardUpdate
}
}
if err != nil && err != plumbing.ErrReferenceNotFound {
return err
}
if err := w.updateHEAD(ref.Hash()); err != nil {
return err
}
if err := w.Reset(&ResetOptions{
Mode: MergeReset,
Commit: ref.Hash(),
}); err != nil {
return err
}
if o.RecurseSubmodules != NoRecurseSubmodules {
return w.updateSubmodules(ctx, &SubmoduleUpdateOptions{
RecurseSubmodules: o.RecurseSubmodules,
Auth: o.Auth,
})
}
return nil
}
func (w *Worktree) updateSubmodules(ctx context.Context, o *SubmoduleUpdateOptions) error {
s, err := w.Submodules()
if err != nil {
return err
}
o.Init = true
return s.UpdateContext(ctx, o)
}
// Checkout switch branches or restore working tree files.
func (w *Worktree) Checkout(opts *CheckoutOptions) error {
if err := opts.Validate(); err != nil {
return err
}
if opts.Create {
if err := w.createBranch(opts); err != nil {
return err
}
}
c, err := w.getCommitFromCheckoutOptions(opts)
if err != nil {
return err
}
ro := &ResetOptions{Commit: c, Mode: MergeReset}
if opts.Force {
ro.Mode = HardReset
} else if opts.Keep {
ro.Mode = SoftReset
}
if !opts.Hash.IsZero() && !opts.Create {
err = w.setHEADToCommit(opts.Hash)
} else {
err = w.setHEADToBranch(opts.Branch, c)
}
if err != nil {
return err
}
if len(opts.SparseCheckoutDirectories) > 0 {
return w.ResetSparsely(ro, opts.SparseCheckoutDirectories)
}
return w.Reset(ro)
}
func (w *Worktree) createBranch(opts *CheckoutOptions) error {
if err := opts.Branch.Validate(); err != nil {
return err
}
_, err := w.r.Storer.Reference(opts.Branch)
if err == nil {
return fmt.Errorf("a branch named %q already exists", opts.Branch)
}
if err != plumbing.ErrReferenceNotFound {
return err
}
if opts.Hash.IsZero() {
ref, err := w.r.Head()
if err != nil {
return err
}
opts.Hash = ref.Hash()
}
return w.r.Storer.SetReference(
plumbing.NewHashReference(opts.Branch, opts.Hash),
)
}
func (w *Worktree) getCommitFromCheckoutOptions(opts *CheckoutOptions) (plumbing.Hash, error) {
hash := opts.Hash
if hash.IsZero() {
b, err := w.r.Reference(opts.Branch, true)
if err != nil {
return plumbing.ZeroHash, err
}
hash = b.Hash()
}
o, err := w.r.Object(plumbing.AnyObject, hash)
if err != nil {
return plumbing.ZeroHash, err
}
switch o := o.(type) {
case *object.Tag:
if o.TargetType != plumbing.CommitObject {
return plumbing.ZeroHash, fmt.Errorf("%w: tag target %q", object.ErrUnsupportedObject, o.TargetType)
}
return o.Target, nil
case *object.Commit:
return o.Hash, nil
}
return plumbing.ZeroHash, fmt.Errorf("%w: %q", object.ErrUnsupportedObject, o.Type())
}
func (w *Worktree) setHEADToCommit(commit plumbing.Hash) error {
head := plumbing.NewHashReference(plumbing.HEAD, commit)
return w.r.Storer.SetReference(head)
}
func (w *Worktree) setHEADToBranch(branch plumbing.ReferenceName, commit plumbing.Hash) error {
target, err := w.r.Storer.Reference(branch)
if err != nil {
return err
}
var head *plumbing.Reference
if target.Name().IsBranch() {
head = plumbing.NewSymbolicReference(plumbing.HEAD, target.Name())
} else {
head = plumbing.NewHashReference(plumbing.HEAD, commit)
}
return w.r.Storer.SetReference(head)
}
func (w *Worktree) ResetSparsely(opts *ResetOptions, dirs []string) error {
if err := opts.Validate(w.r); err != nil {
return err
}
if opts.Mode == MergeReset {
unstaged, err := w.containsUnstagedChanges()
if err != nil {
return err
}
if unstaged {
return ErrUnstagedChanges
}
}
if err := w.setHEADCommit(opts.Commit); err != nil {
return err
}
if opts.Mode == SoftReset {
return nil
}
t, err := w.r.getTreeFromCommitHash(opts.Commit)
if err != nil {
return err
}
if opts.Mode == MixedReset || opts.Mode == MergeReset || opts.Mode == HardReset {
if err := w.resetIndex(t, dirs, opts.Files); err != nil {
return err
}
}
if opts.Mode == MergeReset || opts.Mode == HardReset {
if err := w.resetWorktree(t, opts.Files); err != nil {
return err
}
}
return nil
}
// Restore restores specified files in the working tree or stage with contents from
// a restore source. If a path is tracked but does not exist in the restore,
// source, it will be removed to match the source.
//
// If Staged and Worktree are true, then the restore source will be the index.
// If only Staged is true, then the restore source will be HEAD.
// If only Worktree is true or neither Staged nor Worktree are true, will
// result in ErrRestoreWorktreeOnlyNotSupported because restoring the working
// tree while leaving the stage untouched is not currently supported.
//
// Restore with no files specified will return ErrNoRestorePaths.
func (w *Worktree) Restore(o *RestoreOptions) error {
if err := o.Validate(); err != nil {
return err
}
if o.Staged {
opts := &ResetOptions{
Files: o.Files,
}
if o.Worktree {
// If we are doing both Worktree and Staging then it is a hard reset
opts.Mode = HardReset
} else {
// If we are doing just staging then it is a mixed reset
opts.Mode = MixedReset
}
return w.Reset(opts)
}
return ErrRestoreWorktreeOnlyNotSupported
}
// Reset the worktree to a specified state.
func (w *Worktree) Reset(opts *ResetOptions) error {
return w.ResetSparsely(opts, nil)
}
func (w *Worktree) resetIndex(t *object.Tree, dirs []string, files []string) error {
idx, err := w.r.Storer.Index()
if err != nil {
return err
}
b := newIndexBuilder(idx)
changes, err := w.diffTreeWithStaging(t, true)
if err != nil {
return err
}
for _, ch := range changes {
a, err := ch.Action()
if err != nil {
return err
}
var name string
var e *object.TreeEntry
switch a {
case merkletrie.Modify, merkletrie.Insert:
name = ch.To.String()
e, err = t.FindEntry(name)
if err != nil {
return err
}
case merkletrie.Delete:
name = ch.From.String()
}
if len(files) > 0 {
contains := inFiles(files, name)
if !contains {
continue
}
}
b.Remove(name)
if e == nil {
continue
}
b.Add(&index.Entry{
Name: name,
Hash: e.Hash,
Mode: e.Mode,
})
}
b.Write(idx)
if len(dirs) > 0 {
idx.SkipUnless(dirs)
}
return w.r.Storer.SetIndex(idx)
}
func inFiles(files []string, v string) bool {
for _, s := range files {
if s == v {
return true
}
}
return false
}
func (w *Worktree) resetWorktree(t *object.Tree, files []string) error {
changes, err := w.diffStagingWithWorktree(true, false)
if err != nil {
return err
}
idx, err := w.r.Storer.Index()
if err != nil {
return err
}
b := newIndexBuilder(idx)
for _, ch := range changes {
if err := w.validChange(ch); err != nil {
return err
}
if len(files) > 0 {
file := ""
if ch.From != nil {
file = ch.From.Name()
} else if ch.To != nil {
file = ch.To.Name()
}
if file == "" {
continue
}
contains := inFiles(files, file)
if !contains {
continue
}
}
if err := w.checkoutChange(ch, t, b); err != nil {
return err
}
}
b.Write(idx)
return w.r.Storer.SetIndex(idx)
}
// worktreeDeny is a list of paths that are not allowed
// to be used when resetting the worktree.
var worktreeDeny = map[string]struct{}{
// .git
GitDirName: {},
// For other historical reasons, file names that do not conform to the 8.3
// format (up to eight characters for the basename, three for the file
// extension, certain characters not allowed such as `+`, etc) are associated
// with a so-called "short name", at least on the `C:` drive by default.
// Which means that `git~1/` is a valid way to refer to `.git/`.
"git~1": {},
}
// validPath checks whether paths are valid.
// The rules around invalid paths could differ from upstream based on how
// filesystems are managed within go-git, but they are largely the same.
//
// For upstream rules:
// https://github.com/git/git/blob/564d0252ca632e0264ed670534a51d18a689ef5d/read-cache.c#L946
// https://github.com/git/git/blob/564d0252ca632e0264ed670534a51d18a689ef5d/path.c#L1383
func validPath(paths ...string) error {
for _, p := range paths {
parts := strings.FieldsFunc(p, func(r rune) bool { return (r == '\\' || r == '/') })
if len(parts) == 0 {
return fmt.Errorf("invalid path: %q", p)
}
if _, denied := worktreeDeny[strings.ToLower(parts[0])]; denied {
return fmt.Errorf("invalid path prefix: %q", p)
}
if runtime.GOOS == "windows" {
// Volume names are not supported, in both formats: \\ and <DRIVE_LETTER>:.
if vol := filepath.VolumeName(p); vol != "" {
return fmt.Errorf("invalid path: %q", p)
}
if !windowsValidPath(parts[0]) {
return fmt.Errorf("invalid path: %q", p)
}
}
for _, part := range parts {
if part == ".." {
return fmt.Errorf("invalid path %q: cannot use '..'", p)
}
}
}
return nil
}
// windowsPathReplacer defines the chars that need to be replaced
// as part of windowsValidPath.
var windowsPathReplacer *strings.Replacer
func init() {
windowsPathReplacer = strings.NewReplacer(" ", "", ".", "")
}
func windowsValidPath(part string) bool {
if len(part) > 3 && strings.EqualFold(part[:4], GitDirName) {
// For historical reasons, file names that end in spaces or periods are
// automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
// to `.git/`.
if windowsPathReplacer.Replace(part[4:]) == "" {
return false
}
// For yet other historical reasons, NTFS supports so-called "Alternate Data
// Streams", i.e. metadata associated with a given file, referred to via
// `<filename>:<stream-name>:<stream-type>`. There exists a default stream
// type for directories, allowing `.git/` to be accessed via
// `.git::$INDEX_ALLOCATION/`.
//
// For performance reasons, _all_ Alternate Data Streams of `.git/` are
// forbidden, not just `::$INDEX_ALLOCATION`.
if len(part) > 4 && part[4:5] == ":" {
return false
}
}
return true
}
func (w *Worktree) validChange(ch merkletrie.Change) error {
action, err := ch.Action()
if err != nil {
return nil
}
switch action {
case merkletrie.Delete:
return validPath(ch.From.String())
case merkletrie.Insert:
return validPath(ch.To.String())
case merkletrie.Modify:
return validPath(ch.From.String(), ch.To.String())
}
return nil
}
func (w *Worktree) checkoutChange(ch merkletrie.Change, t *object.Tree, idx *indexBuilder) error {
a, err := ch.Action()
if err != nil {
return err
}
var e *object.TreeEntry
var name string
var isSubmodule bool
switch a {
case merkletrie.Modify, merkletrie.Insert:
name = ch.To.String()
e, err = t.FindEntry(name)
if err != nil {
return err
}
isSubmodule = e.Mode == filemode.Submodule
case merkletrie.Delete:
return rmFileAndDirsIfEmpty(w.Filesystem, ch.From.String())
}
if isSubmodule {
return w.checkoutChangeSubmodule(name, a, e, idx)
}
return w.checkoutChangeRegularFile(name, a, t, e, idx)
}
func (w *Worktree) containsUnstagedChanges() (bool, error) {
ch, err := w.diffStagingWithWorktree(false, true)
if err != nil {
return false, err
}
for _, c := range ch {
a, err := c.Action()
if err != nil {
return false, err
}
if a == merkletrie.Insert {
continue
}
return true, nil
}
return false, nil
}
func (w *Worktree) setHEADCommit(commit plumbing.Hash) error {
head, err := w.r.Reference(plumbing.HEAD, false)
if err != nil {
return err
}
if head.Type() == plumbing.HashReference {
head = plumbing.NewHashReference(plumbing.HEAD, commit)
return w.r.Storer.SetReference(head)
}
branch, err := w.r.Reference(head.Target(), false)
if err != nil {
return err
}
if !branch.Name().IsBranch() {
return fmt.Errorf("invalid HEAD target should be a branch, found %s", branch.Type())
}
branch = plumbing.NewHashReference(branch.Name(), commit)
return w.r.Storer.SetReference(branch)
}
func (w *Worktree) checkoutChangeSubmodule(name string,
a merkletrie.Action,
e *object.TreeEntry,
idx *indexBuilder,
) error {
switch a {
case merkletrie.Modify:
sub, err := w.Submodule(name)
if err != nil {
return err
}
if !sub.initialized {
return nil
}
return w.addIndexFromTreeEntry(name, e, idx)
case merkletrie.Insert:
mode, err := e.Mode.ToOSFileMode()
if err != nil {
return err
}
if err := w.Filesystem.MkdirAll(name, mode); err != nil {
return err
}
return w.addIndexFromTreeEntry(name, e, idx)
}
return nil
}
func (w *Worktree) checkoutChangeRegularFile(name string,
a merkletrie.Action,
t *object.Tree,
e *object.TreeEntry,
idx *indexBuilder,
) error {
switch a {
case merkletrie.Modify:
idx.Remove(name)
// to apply perm changes the file is deleted, billy doesn't implement
// chmod
if err := w.Filesystem.Remove(name); err != nil {
return err
}
fallthrough
case merkletrie.Insert:
f, err := t.File(name)
if err != nil {
return err
}
if err := w.checkoutFile(f); err != nil {
return err
}
return w.addIndexFromFile(name, e.Hash, f.Mode, idx)
}
return nil
}
func (w *Worktree) checkoutFile(f *object.File) (err error) {
mode, err := f.Mode.ToOSFileMode()
if err != nil {
return
}
if mode&os.ModeSymlink != 0 {
return w.checkoutFileSymlink(f)
}
from, err := f.Reader()
if err != nil {
return
}
defer ioutil.CheckClose(from, &err)
to, err := w.Filesystem.OpenFile(f.Name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode.Perm())
if err != nil {
return
}
defer ioutil.CheckClose(to, &err)
buf := sync.GetByteSlice()
_, err = io.CopyBuffer(to, from, *buf)
sync.PutByteSlice(buf)
return
}
func (w *Worktree) checkoutFileSymlink(f *object.File) (err error) {
// https://github.com/git/git/commit/10ecfa76491e4923988337b2e2243b05376b40de
if strings.EqualFold(f.Name, gitmodulesFile) {
return ErrGitModulesSymlink
}
from, err := f.Reader()
if err != nil {
return
}
defer ioutil.CheckClose(from, &err)
bytes, err := io.ReadAll(from)
if err != nil {
return
}
err = w.Filesystem.Symlink(string(bytes), f.Name)
// On windows, this might fail.
// Follow Git on Windows behavior by writing the link as it is.
if err != nil && isSymlinkWindowsNonAdmin(err) {
mode, _ := f.Mode.ToOSFileMode()
to, err := w.Filesystem.OpenFile(f.Name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode.Perm())
if err != nil {
return err
}
defer ioutil.CheckClose(to, &err)
_, err = to.Write(bytes)
return err
}
return
}
func (w *Worktree) addIndexFromTreeEntry(name string, f *object.TreeEntry, idx *indexBuilder) error {
idx.Remove(name)
idx.Add(&index.Entry{
Hash: f.Hash,
Name: name,
Mode: filemode.Submodule,
})
return nil
}
func (w *Worktree) addIndexFromFile(name string, h plumbing.Hash, mode filemode.FileMode, idx *indexBuilder) error {
idx.Remove(name)
fi, err := w.Filesystem.Lstat(name)
if err != nil {
return err
}
e := &index.Entry{
Hash: h,
Name: name,
Mode: mode,
ModifiedAt: fi.ModTime(),
Size: uint32(fi.Size()),
}
// if the FileInfo.Sys() comes from os the ctime, dev, inode, uid and gid
// can be retrieved, otherwise this doesn't apply
if fillSystemInfo != nil {
fillSystemInfo(e, fi.Sys())
}
idx.Add(e)
return nil
}
func (r *Repository) getTreeFromCommitHash(commit plumbing.Hash) (*object.Tree, error) {
c, err := r.CommitObject(commit)
if err != nil {
return nil, err
}
return c.Tree()
}
var fillSystemInfo func(e *index.Entry, sys interface{})
const gitmodulesFile = ".gitmodules"
// Submodule returns the submodule with the given name
func (w *Worktree) Submodule(name string) (*Submodule, error) {
l, err := w.Submodules()
if err != nil {
return nil, err
}
for _, m := range l {
if m.Config().Name == name {
return m, nil
}
}
return nil, ErrSubmoduleNotFound
}
// Submodules returns all the available submodules
func (w *Worktree) Submodules() (Submodules, error) {
l := make(Submodules, 0)
m, err := w.readGitmodulesFile()
if err != nil || m == nil {
return l, err
}
c, err := w.r.Config()
if err != nil {
return nil, err
}
for _, s := range m.Submodules {
l = append(l, w.newSubmodule(s, c.Submodules[s.Name]))
}
return l, nil
}
func (w *Worktree) newSubmodule(fromModules, fromConfig *config.Submodule) *Submodule {
m := &Submodule{w: w}
m.initialized = fromConfig != nil
if !m.initialized {
m.c = fromModules
return m
}
m.c = fromConfig
m.c.Path = fromModules.Path
return m
}
func (w *Worktree) isSymlink(path string) bool {
if s, err := w.Filesystem.Lstat(path); err == nil {
return s.Mode()&os.ModeSymlink != 0
}
return false
}
func (w *Worktree) readGitmodulesFile() (*config.Modules, error) {
if w.isSymlink(gitmodulesFile) {
return nil, ErrGitModulesSymlink
}
f, err := w.Filesystem.Open(gitmodulesFile)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
defer f.Close()
input, err := io.ReadAll(f)
if err != nil {
return nil, err
}
m := config.NewModules()
if err := m.Unmarshal(input); err != nil {
return m, err
}
return m, nil
}
// Clean the worktree by removing untracked files.
// An empty dir could be removed - this is what `git clean -f -d .` does.
func (w *Worktree) Clean(opts *CleanOptions) error {
s, err := w.Status()
if err != nil {
return err
}
root := ""
files, err := w.Filesystem.ReadDir(root)
if err != nil {
return err
}
return w.doClean(s, opts, root, files)
}
func (w *Worktree) doClean(status Status, opts *CleanOptions, dir string, files []os.FileInfo) error {
for _, fi := range files {
if fi.Name() == GitDirName {
continue
}
// relative path under the root
path := filepath.Join(dir, fi.Name())
if fi.IsDir() {
if !opts.Dir {
continue
}
subfiles, err := w.Filesystem.ReadDir(path)
if err != nil {
return err
}
err = w.doClean(status, opts, path, subfiles)
if err != nil {
return err
}
} else {
if status.IsUntracked(path) {
if err := w.Filesystem.Remove(path); err != nil {
return err
}
}
}
}
if opts.Dir && dir != "" {
_, err := removeDirIfEmpty(w.Filesystem, dir)
return err
}
return nil
}
// GrepResult is structure of a grep result.
type GrepResult struct {
// FileName is the name of file which contains match.
FileName string
// LineNumber is the line number of a file at which a match was found.
LineNumber int
// Content is the content of the file at the matching line.
Content string
// TreeName is the name of the tree (reference name/commit hash) at
// which the match was performed.
TreeName string
}
func (gr GrepResult) String() string {
return fmt.Sprintf("%s:%s:%d:%s", gr.TreeName, gr.FileName, gr.LineNumber, gr.Content)
}
// Grep performs grep on a repository.
func (r *Repository) Grep(opts *GrepOptions) ([]GrepResult, error) {
if err := opts.validate(r); err != nil {
return nil, err
}