Debian Codegraph @

utils/merkletrie/index/node.go

raw
1 package index
2
3 import (
4 "path"
5 "strings"
6
7 "github.com/go-git/go-git/v5/plumbing/format/index"
8 "github.com/go-git/go-git/v5/utils/merkletrie/noder"
9 )
10
11 // The node represents a index.Entry or a directory inferred from the path
12 // of all entries. It implements the interface noder.Noder of merkletrie
13 // package.
14 //
15 // This implementation implements a "standard" hash method being able to be
16 // compared with any other noder.Noder implementation inside of go-git
17 type node struct {
18 path string
19 entry *index.Entry
20 children []noder.Noder
21 isDir bool
22 skip bool
23 }
24
25 // NewRootNode returns the root node of a computed tree from a index.Index,
26 func NewRootNode(idx *index.Index) noder.Noder {
27 const rootNode = ""
28
29 m := map[string]*node{rootNode: {isDir: true}}
30
31 for _, e := range idx.Entries {
32 parts := strings.Split(e.Name, string("/"))
33
34 var fullpath string
35 for _, part := range parts {
36 parent := fullpath
37 fullpath = path.Join(fullpath, part)
38
39 // It's possible that the first occurrence of subdirectory is skipped.
40 // The parent node can be created with SkipWorktree set to true, but
41 // if any future children do not skip their subtree, the entire lineage
42 // of the tree needs to have this value set to false so that subdirectories
43 // are not ignored.
44 if parentNode, ok := m[fullpath]; ok {
45 if e.SkipWorktree == false {
46 parentNode.skip = false
47 }
48 continue
49 }
50
51 n := &node{path: fullpath, skip: e.SkipWorktree}
52 if fullpath == e.Name {
53 n.entry = e
54 } else {
55 n.isDir = true
56 }
57
58 m[n.path] = n
59 m[parent].children = append(m[parent].children, n)
60 }
61 }
62
63 return m[rootNode]
64 }
65
66 func (n *node) String() string {
67 return n.path
68 }
69
70 func (n *node) Skip() bool {
71 return n.skip
72 }
73
74 // Hash the hash of a filesystem is a 24-byte slice, is the result of
75 // concatenating the computed plumbing.Hash of the file as a Blob and its
76 // plumbing.FileMode; that way the difftree algorithm will detect changes in the
77 // contents of files and also in their mode.
78 //
79 // If the node is computed and not based on a index.Entry the hash is equals
80 // to a 24-bytes slices of zero values.
81 func (n *node) Hash() []byte {
82 if n.entry == nil {
83 return make([]byte, 24)
84 }
85
86 return append(n.entry.Hash[:], n.entry.Mode.Bytes()...)
87 }
88
89 func (n *node) Name() string {
90 return path.Base(n.path)
91 }
92
93 func (n *node) IsDir() bool {
94 return n.isDir
95 }
96
97 func (n *node) Children() ([]noder.Noder, error) {
98 return n.children, nil
99 }
100
101 func (n *node) NumChildren() (int, error) {
102 return len(n.children), nil
103 }