Debian Codegraph @

worktree_status.go

raw
1 package git
2
3 import (
4 "bytes"
5 "errors"
6 "io"
7 "os"
8 "path"
9 "path/filepath"
10 "strings"
11
12 "github.com/go-git/go-billy/v5/util"
13 "github.com/go-git/go-git/v5/internal/pathutil"
14 "github.com/go-git/go-git/v5/plumbing"
15 "github.com/go-git/go-git/v5/plumbing/filemode"
16 "github.com/go-git/go-git/v5/plumbing/format/gitignore"
17 "github.com/go-git/go-git/v5/plumbing/format/index"
18 "github.com/go-git/go-git/v5/plumbing/object"
19 "github.com/go-git/go-git/v5/utils/ioutil"
20 "github.com/go-git/go-git/v5/utils/merkletrie"
21 "github.com/go-git/go-git/v5/utils/merkletrie/filesystem"
22 mindex "github.com/go-git/go-git/v5/utils/merkletrie/index"
23 "github.com/go-git/go-git/v5/utils/merkletrie/noder"
24 )
25
26 var (
27 // ErrDestinationExists in an Move operation means that the target exists on
28 // the worktree.
29 ErrDestinationExists = errors.New("destination exists")
30 // ErrGlobNoMatches in an AddGlob if the glob pattern does not match any
31 // files in the worktree.
32 ErrGlobNoMatches = errors.New("glob pattern did not match any files")
33 // ErrUnsupportedStatusStrategy occurs when an invalid StatusStrategy is used
34 // when processing the Worktree status.
35 ErrUnsupportedStatusStrategy = errors.New("unsupported status strategy")
36 )
37
38 // Status returns the working tree status.
39 func (w *Worktree) Status() (Status, error) {
40 return w.StatusWithOptions(StatusOptions{Strategy: defaultStatusStrategy})
41 }
42
43 // StatusOptions defines the options for Worktree.StatusWithOptions().
44 type StatusOptions struct {
45 Strategy StatusStrategy
46 }
47
48 // StatusWithOptions returns the working tree status.
49 func (w *Worktree) StatusWithOptions(o StatusOptions) (Status, error) {
50 var hash plumbing.Hash
51
52 ref, err := w.r.Head()
53 if err != nil && err != plumbing.ErrReferenceNotFound {
54 return nil, err
55 }
56
57 if err == nil {
58 hash = ref.Hash()
59 }
60
61 return w.status(o.Strategy, hash)
62 }
63
64 func (w *Worktree) status(ss StatusStrategy, commit plumbing.Hash) (Status, error) {
65 s, err := ss.new(w)
66 if err != nil {
67 return nil, err
68 }
69
70 left, err := w.diffCommitWithStaging(commit, false)
71 if err != nil {
72 return nil, err
73 }
74
75 for _, ch := range left {
76 a, err := ch.Action()
77 if err != nil {
78 return nil, err
79 }
80
81 fs := s.File(nameFromAction(&ch))
82 fs.Worktree = Unmodified
83
84 switch a {
85 case merkletrie.Delete:
86 s.File(ch.From.String()).Staging = Deleted
87 case merkletrie.Insert:
88 s.File(ch.To.String()).Staging = Added
89 case merkletrie.Modify:
90 s.File(ch.To.String()).Staging = Modified
91 }
92 }
93
94 right, err := w.diffStagingWithWorktree(false, true)
95 if err != nil {
96 return nil, err
97 }
98
99 for _, ch := range right {
100 a, err := ch.Action()
101 if err != nil {
102 return nil, err
103 }
104
105 fs := s.File(nameFromAction(&ch))
106 if fs.Staging == Untracked {
107 fs.Staging = Unmodified
108 }
109
110 switch a {
111 case merkletrie.Delete:
112 fs.Worktree = Deleted
113 case merkletrie.Insert:
114 fs.Worktree = Untracked
115 fs.Staging = Untracked
116 case merkletrie.Modify:
117 fs.Worktree = Modified
118 }
119 }
120
121 return s, nil
122 }
123
124 func nameFromAction(ch *merkletrie.Change) string {
125 name := ch.To.String()
126 if name == "" {
127 return ch.From.String()
128 }
129
130 return name
131 }
132
133 func (w *Worktree) diffStagingWithWorktree(reverse, excludeIgnoredChanges bool) (merkletrie.Changes, error) {
134 idx, err := w.r.Storer.Index()
135 if err != nil {
136 return nil, err
137 }
138
139 from := mindex.NewRootNode(idx)
140 submodules, err := w.getSubmodulesStatus()
141 if err != nil {
142 return nil, err
143 }
144
145 to := filesystem.NewRootNodeWithOptions(w.Filesystem, submodules, filesystem.Options{Index: idx})
146
147 var c merkletrie.Changes
148 if reverse {
149 c, err = merkletrie.DiffTree(to, from, diffTreeIsEquals)
150 } else {
151 c, err = merkletrie.DiffTree(from, to, diffTreeIsEquals)
152 }
153
154 if err != nil {
155 return nil, err
156 }
157
158 if excludeIgnoredChanges {
159 return w.excludeIgnoredChanges(c), nil
160 }
161 return c, nil
162 }
163
164 func (w *Worktree) excludeIgnoredChanges(changes merkletrie.Changes) merkletrie.Changes {
165 patterns, err := gitignore.ReadPatterns(w.Filesystem, nil)
166 if err != nil {
167 return changes
168 }
169
170 patterns = append(patterns, w.Excludes...)
171
172 if len(patterns) == 0 {
173 return changes
174 }
175
176 m := gitignore.NewMatcher(patterns)
177
178 var res merkletrie.Changes
179 for _, ch := range changes {
180 var path []string
181 for _, n := range ch.To {
182 path = append(path, n.Name())
183 }
184 if len(path) == 0 {
185 for _, n := range ch.From {
186 path = append(path, n.Name())
187 }
188 }
189 if len(path) != 0 {
190 isDir := (len(ch.To) > 0 && ch.To.IsDir()) || (len(ch.From) > 0 && ch.From.IsDir())
191 if m.Match(path, isDir) {
192 if len(ch.From) == 0 {
193 continue
194 }
195 }
196 }
197 res = append(res, ch)
198 }
199 return res
200 }
201
202 func (w *Worktree) getSubmodulesStatus() (map[string]plumbing.Hash, error) {
203 o := map[string]plumbing.Hash{}
204
205 sub, err := w.Submodules()
206 if err != nil {
207 return nil, err
208 }
209
210 status, err := sub.Status()
211 if err != nil {
212 return nil, err
213 }
214
215 for _, s := range status {
216 if s.Current.IsZero() {
217 o[s.Path] = s.Expected
218 continue
219 }
220
221 o[s.Path] = s.Current
222 }
223
224 return o, nil
225 }
226
227 func (w *Worktree) diffCommitWithStaging(commit plumbing.Hash, reverse bool) (merkletrie.Changes, error) {
228 var t *object.Tree
229 if !commit.IsZero() {
230 c, err := w.r.CommitObject(commit)
231 if err != nil {
232 return nil, err
233 }
234
235 t, err = c.Tree()
236 if err != nil {
237 return nil, err
238 }
239 }
240
241 return w.diffTreeWithStaging(t, reverse)
242 }
243
244 func (w *Worktree) diffTreeWithStaging(t *object.Tree, reverse bool) (merkletrie.Changes, error) {
245 var from noder.Noder
246 if t != nil {
247 from = object.NewTreeRootNode(t)
248 }
249
250 idx, err := w.r.Storer.Index()
251 if err != nil {
252 return nil, err
253 }
254
255 to := mindex.NewRootNode(idx)
256
257 if reverse {
258 return merkletrie.DiffTree(to, from, diffTreeIsEquals)
259 }
260
261 return merkletrie.DiffTree(from, to, diffTreeIsEquals)
262 }
263
264 var emptyNoderHash = make([]byte, 24)
265
266 // diffTreeIsEquals is a implementation of noder.Equals, used to compare
267 // noder.Noder, it compare the content and the length of the hashes.
268 //
269 // Since some of the noder.Noder implementations doesn't compute a hash for
270 // some directories, if any of the hashes is a 24-byte slice of zero values
271 // the comparison is not done and the hashes are take as different.
272 func diffTreeIsEquals(a, b noder.Hasher) bool {
273 hashA := a.Hash()
274 hashB := b.Hash()
275
276 if bytes.Equal(hashA, emptyNoderHash) || bytes.Equal(hashB, emptyNoderHash) {
277 return false
278 }
279
280 return bytes.Equal(hashA, hashB)
281 }
282
283 // Add adds the file contents of a file in the worktree to the index. if the
284 // file is already staged in the index no error is returned. If a file deleted
285 // from the Workspace is given, the file is removed from the index. If a
286 // directory given, adds the files and all his sub-directories recursively in
287 // the worktree to the index. If any of the files is already staged in the index
288 // no error is returned. When path is a file, the blob.Hash is returned.
289 func (w *Worktree) Add(path string) (plumbing.Hash, error) {
290 // TODO(mcuadros): deprecate in favor of AddWithOption in v6.
291 return w.doAdd(path, make([]gitignore.Pattern, 0), false)
292 }
293
294 func (w *Worktree) doAddDirectory(idx *index.Index, s Status, directory string, ignorePattern []gitignore.Pattern) (added bool, err error) {
295 if len(ignorePattern) > 0 {
296 m := gitignore.NewMatcher(ignorePattern)
297 matchPath := strings.Split(directory, string(os.PathSeparator))
298 if m.Match(matchPath, true) {
299 // ignore
300 return false, nil
301 }
302 }
303
304 directory = filepath.ToSlash(filepath.Clean(directory))
305
306 for name := range s {
307 if !isPathInDirectory(name, directory) {
308 continue
309 }
310
311 var a bool
312 a, _, err = w.doAddFile(idx, s, name, ignorePattern)
313 if err != nil {
314 return
315 }
316
317 added = added || a
318 }
319
320 return
321 }
322
323 func isPathInDirectory(path, directory string) bool {
324 return directory == "." || strings.HasPrefix(path, directory+"/")
325 }
326
327 // AddWithOptions file contents to the index, updates the index using the
328 // current content found in the working tree, to prepare the content staged for
329 // the next commit.
330 //
331 // It typically adds the current content of existing paths as a whole, but with
332 // some options it can also be used to add content with only part of the changes
333 // made to the working tree files applied, or remove paths that do not exist in
334 // the working tree anymore.
335 func (w *Worktree) AddWithOptions(opts *AddOptions) error {
336 if err := opts.Validate(w.r); err != nil {
337 return err
338 }
339
340 if opts.All {
341 _, err := w.doAdd(".", w.Excludes, false)
342 return err
343 }
344
345 if opts.Glob != "" {
346 return w.AddGlob(opts.Glob)
347 }
348
349 _, err := w.doAdd(opts.Path, make([]gitignore.Pattern, 0), opts.SkipStatus)
350 return err
351 }
352
353 func (w *Worktree) doAdd(path string, ignorePattern []gitignore.Pattern, skipStatus bool) (plumbing.Hash, error) {
354 idx, err := w.r.Storer.Index()
355 if err != nil {
356 return plumbing.ZeroHash, err
357 }
358
359 var h plumbing.Hash
360 var added bool
361
362 fi, err := w.Filesystem.Lstat(path)
363
364 // status is required for doAddDirectory
365 var s Status
366 var err2 error
367 if !skipStatus || fi == nil || fi.IsDir() {
368 s, err2 = w.Status()
369 if err2 != nil {
370 return plumbing.ZeroHash, err2
371 }
372 }
373
374 path = filepath.ToSlash(filepath.Clean(path))
375
376 if err != nil || !fi.IsDir() {
377 added, h, err = w.doAddFile(idx, s, path, ignorePattern)
378 } else {
379 added, err = w.doAddDirectory(idx, s, path, ignorePattern)
380 }
381
382 if err != nil {
383 return h, err
384 }
385
386 if !added {
387 return h, nil
388 }
389
390 return h, w.r.Storer.SetIndex(idx)
391 }
392
393 // AddGlob adds all paths, matching pattern, to the index. If pattern matches a
394 // directory path, all directory contents are added to the index recursively. No
395 // error is returned if all matching paths are already staged in index.
396 func (w *Worktree) AddGlob(pattern string) error {
397 // TODO(mcuadros): deprecate in favor of AddWithOption in v6.
398 files, err := util.Glob(w.Filesystem, pattern)
399 if err != nil {
400 return err
401 }
402
403 if len(files) == 0 {
404 return ErrGlobNoMatches
405 }
406
407 s, err := w.Status()
408 if err != nil {
409 return err
410 }
411
412 idx, err := w.r.Storer.Index()
413 if err != nil {
414 return err
415 }
416
417 var saveIndex bool
418 for _, file := range files {
419 fi, err := w.Filesystem.Lstat(file)
420 if err != nil {
421 return err
422 }
423
424 var added bool
425 if fi.IsDir() {
426 added, err = w.doAddDirectory(idx, s, file, make([]gitignore.Pattern, 0))
427 } else {
428 added, _, err = w.doAddFile(idx, s, file, make([]gitignore.Pattern, 0))
429 }
430
431 if err != nil {
432 return err
433 }
434
435 if !saveIndex && added {
436 saveIndex = true
437 }
438 }
439
440 if saveIndex {
441 return w.r.Storer.SetIndex(idx)
442 }
443
444 return nil
445 }
446
447 // doAddFile create a new blob from path and update the index, added is true if
448 // the file added is different from the index.
449 // if s status is nil will skip the status check and update the index anyway
450 func (w *Worktree) doAddFile(idx *index.Index, s Status, path string, ignorePattern []gitignore.Pattern) (added bool, h plumbing.Hash, err error) {
451 if s != nil && s.File(path).Worktree == Unmodified {
452 return false, h, nil
453 }
454 if len(ignorePattern) > 0 {
455 m := gitignore.NewMatcher(ignorePattern)
456 matchPath := strings.Split(path, string(os.PathSeparator))
457 if m.Match(matchPath, true) {
458 // ignore
459 return false, h, nil
460 }
461 }
462
463 h, err = w.copyFileToStorage(path)
464 if err != nil {
465 if os.IsNotExist(err) {
466 added = true
467 h, err = w.deleteFromIndex(idx, path)
468 }
469
470 return
471 }
472
473 if err := w.addOrUpdateFileToIndex(idx, path, h); err != nil {
474 return false, h, err
475 }
476
477 return true, h, err
478 }
479
480 func (w *Worktree) copyFileToStorage(path string) (hash plumbing.Hash, err error) {
481 fi, err := w.Filesystem.Lstat(path)
482 if err != nil {
483 return plumbing.ZeroHash, err
484 }
485
486 obj := w.r.Storer.NewEncodedObject()
487 obj.SetType(plumbing.BlobObject)
488 obj.SetSize(fi.Size())
489
490 writer, err := obj.Writer()
491 if err != nil {
492 return plumbing.ZeroHash, err
493 }
494
495 defer ioutil.CheckClose(writer, &err)
496
497 if fi.Mode()&os.ModeSymlink != 0 {
498 err = w.fillEncodedObjectFromSymlink(writer, path, fi)
499 } else {
500 err = w.fillEncodedObjectFromFile(writer, path, fi)
501 }
502
503 if err != nil {
504 return plumbing.ZeroHash, err
505 }
506
507 return w.r.Storer.SetEncodedObject(obj)
508 }
509
510 func (w *Worktree) fillEncodedObjectFromFile(dst io.Writer, path string, _ os.FileInfo) (err error) {
511 src, err := w.Filesystem.Open(path)
512 if err != nil {
513 return err
514 }
515
516 defer ioutil.CheckClose(src, &err)
517
518 if _, err := io.Copy(dst, src); err != nil {
519 return err
520 }
521
522 return err
523 }
524
525 func (w *Worktree) fillEncodedObjectFromSymlink(dst io.Writer, path string, _ os.FileInfo) error {
526 target, err := w.Filesystem.Readlink(path)
527 if err != nil {
528 return err
529 }
530
531 _, err = dst.Write([]byte(target))
532 return err
533 }
534
535 func (w *Worktree) addOrUpdateFileToIndex(idx *index.Index, filename string, h plumbing.Hash) error {
536 e, err := idx.Entry(filename)
537 if err != nil && err != index.ErrEntryNotFound {
538 return err
539 }
540
541 if err == index.ErrEntryNotFound {
542 return w.doAddFileToIndex(idx, filename, h)
543 }
544
545 return w.doUpdateFileToIndex(e, filename, h)
546 }
547
548 func (w *Worktree) doAddFileToIndex(idx *index.Index, filename string, h plumbing.Hash) error {
549 // Mirror upstream's Index.Add gate at the v5 caller boundary: the
550 // index feeds future trees, so a name that the tree-side
551 // pathutil.ValidTreePath gate would reject must not enter the
552 // index in the first place. v5 keeps Index.Add's existing signature
553 // for API compatibility, so the validation happens here.
554 if err := pathutil.ValidTreePath(filename); err != nil {
555 return err
556 }
557 return w.doUpdateFileToIndex(idx.Add(filename), filename, h)
558 }
559
560 func (w *Worktree) doUpdateFileToIndex(e *index.Entry, filename string, h plumbing.Hash) error {
561 info, err := w.Filesystem.Lstat(filename)
562 if err != nil {
563 return err
564 }
565
566 e.Hash = h
567 e.ModifiedAt = info.ModTime()
568 e.Mode, err = filemode.NewFromOSFileMode(info.Mode())
569 if err != nil {
570 return err
571 }
572
573 // The entry size must always reflect the current state, otherwise
574 // it will cause go-git's Worktree.Status() to divert from "git status".
575 // The size of a symlink is the length of the path to the target.
576 // The size of Regular and Executable files is the size of the files.
577 e.Size = uint32(info.Size())
578
579 fillSystemInfo(e, info.Sys())
580 return nil
581 }
582
583 // Remove removes files from the working tree and from the index.
584 func (w *Worktree) Remove(path string) (plumbing.Hash, error) {
585 // TODO(mcuadros): remove plumbing.Hash from signature at v5.
586 idx, err := w.r.Storer.Index()
587 if err != nil {
588 return plumbing.ZeroHash, err
589 }
590
591 var h plumbing.Hash
592
593 fi, err := w.Filesystem.Lstat(path)
594 if err != nil || !fi.IsDir() {
595 h, err = w.doRemoveFile(idx, path)
596 } else {
597 _, err = w.doRemoveDirectory(idx, path)
598 }
599 if err != nil {
600 return h, err
601 }
602
603 return h, w.r.Storer.SetIndex(idx)
604 }
605
606 func (w *Worktree) doRemoveDirectory(idx *index.Index, directory string) (removed bool, err error) {
607 files, err := w.Filesystem.ReadDir(directory)
608 if err != nil {
609 return false, err
610 }
611
612 for _, file := range files {
613 name := path.Join(directory, file.Name())
614
615 var r bool
616 if file.IsDir() {
617 r, err = w.doRemoveDirectory(idx, name)
618 } else {
619 _, err = w.doRemoveFile(idx, name)
620 if err == index.ErrEntryNotFound {
621 err = nil
622 }
623 }
624
625 if err != nil {
626 return
627 }
628
629 if !removed && r {
630 removed = true
631 }
632 }
633
634 err = w.removeEmptyDirectory(directory)
635 return
636 }
637
638 func (w *Worktree) removeEmptyDirectory(path string) error {
639 files, err := w.Filesystem.ReadDir(path)
640 if err != nil {
641 return err
642 }
643
644 if len(files) != 0 {
645 return nil
646 }
647
648 return w.Filesystem.Remove(path)
649 }
650
651 func (w *Worktree) doRemoveFile(idx *index.Index, path string) (plumbing.Hash, error) {
652 hash, err := w.deleteFromIndex(idx, path)
653 if err != nil {
654 return plumbing.ZeroHash, err
655 }
656
657 return hash, w.deleteFromFilesystem(path)
658 }
659
660 func (w *Worktree) deleteFromIndex(idx *index.Index, path string) (plumbing.Hash, error) {
661 e, err := idx.Remove(path)
662 if err != nil {
663 return plumbing.ZeroHash, err
664 }
665
666 return e.Hash, nil
667 }
668
669 func (w *Worktree) deleteFromFilesystem(path string) error {
670 err := w.Filesystem.Remove(path)
671 if os.IsNotExist(err) {
672 return nil
673 }
674
675 return err
676 }
677
678 // RemoveGlob removes all paths, matching pattern, from the index. If pattern
679 // matches a directory path, all directory contents are removed from the index
680 // recursively.
681 func (w *Worktree) RemoveGlob(pattern string) error {
682 idx, err := w.r.Storer.Index()
683 if err != nil {
684 return err
685 }
686
687 entries, err := idx.Glob(pattern)
688 if err != nil {
689 return err
690 }
691
692 for _, e := range entries {
693 file := filepath.FromSlash(e.Name)
694 if _, err := w.Filesystem.Lstat(file); err != nil && !os.IsNotExist(err) {
695 return err
696 }
697
698 if _, err := w.doRemoveFile(idx, file); err != nil {
699 return err
700 }
701
702 dir, _ := filepath.Split(file)
703 if err := w.removeEmptyDirectory(dir); err != nil {
704 return err
705 }
706 }
707
708 return w.r.Storer.SetIndex(idx)
709 }
710
711 // Move moves or rename a file in the worktree and the index, directories are
712 // not supported.
713 func (w *Worktree) Move(from, to string) (plumbing.Hash, error) {
714 // TODO(mcuadros): support directories and/or implement support for glob
715 if _, err := w.Filesystem.Lstat(from); err != nil {
716 return plumbing.ZeroHash, err
717 }
718
719 if _, err := w.Filesystem.Lstat(to); err == nil {
720 return plumbing.ZeroHash, ErrDestinationExists
721 }
722
723 idx, err := w.r.Storer.Index()
724 if err != nil {
725 return plumbing.ZeroHash, err
726 }
727
728 hash, err := w.deleteFromIndex(idx, from)
729 if err != nil {
730 return plumbing.ZeroHash, err
731 }
732
733 if err := w.Filesystem.Rename(from, to); err != nil {
734 return hash, err
735 }
736
737 if err := w.addOrUpdateFileToIndex(idx, to, hash); err != nil {
738 return hash, err
739 }
740
741 return hash, w.r.Storer.SetIndex(idx)
742 }