Debian Codegraph @

utils/merkletrie/filesystem/node.go

raw
1 package filesystem
2
3 import (
4 "io"
5 "os"
6 "path"
7 "time"
8
9 "github.com/go-git/go-git/v5/plumbing"
10 "github.com/go-git/go-git/v5/plumbing/filemode"
11 "github.com/go-git/go-git/v5/plumbing/format/index"
12 "github.com/go-git/go-git/v5/utils/merkletrie/noder"
13
14 "github.com/go-git/go-billy/v5"
15 )
16
17 var ignore = map[string]bool{
18 ".git": true,
19 }
20
21 // Options contains configuration for the filesystem node.
22 type Options struct {
23 // Index is used to enable the metadata-first comparison optimization while
24 // correctly handling the "racy git" condition. If no index is provided,
25 // the function works without the optimization.
26 Index *index.Index
27 }
28
29 // The node represents a file or a directory in a billy.Filesystem. It
30 // implements the interface noder.Noder of merkletrie package.
31 //
32 // This implementation implements a "standard" hash method being able to be
33 // compared with any other noder.Noder implementation inside of go-git.
34 type node struct {
35 fs billy.Filesystem
36 submodules map[string]plumbing.Hash
37 idx *index.Index
38 idxMap map[string]*index.Entry
39
40 path string
41 hash []byte
42 children []noder.Noder
43 isDir bool
44 mode os.FileMode
45 size int64
46 modTime time.Time
47 }
48
49 // NewRootNode returns the root node based on a given billy.Filesystem.
50 //
51 // In order to provide the submodule hash status, a map[string]plumbing.Hash
52 // should be provided where the key is the path of the submodule and the commit
53 // of the submodule HEAD
54 func NewRootNode(
55 fs billy.Filesystem,
56 submodules map[string]plumbing.Hash,
57 ) noder.Noder {
58 return NewRootNodeWithOptions(fs, submodules, Options{})
59 }
60
61 // NewRootNodeWithOptions returns the root node based on a given billy.Filesystem
62 // with options to set an index. Providing an index enables the metadata-first
63 // comparison optimization while correctly handling the "racy git" condition. If
64 // no index is provided, the function works without the optimization.
65 //
66 // The index's ModTime field is used to detect the racy git condition. When a file's
67 // mtime equals or is newer than the index ModTime, we must hash the file content
68 // even if other metadata matches, because the file may have been modified in the
69 // same second that the index was written.
70 //
71 // Reference: https://git-scm.com/docs/racy-git
72 func NewRootNodeWithOptions(
73 fs billy.Filesystem,
74 submodules map[string]plumbing.Hash,
75 options Options,
76 ) noder.Noder {
77 var idxMap map[string]*index.Entry
78
79 if options.Index != nil {
80 idxMap = make(map[string]*index.Entry, len(options.Index.Entries))
81 for _, entry := range options.Index.Entries {
82 idxMap[entry.Name] = entry
83 }
84 }
85
86 return &node{
87 fs: fs,
88 submodules: submodules,
89 idx: options.Index,
90 idxMap: idxMap,
91 isDir: true,
92 }
93 }
94
95 // Hash the hash of a filesystem is the result of concatenating the computed
96 // plumbing.Hash of the file as a Blob and its plumbing.FileMode; that way the
97 // difftree algorithm will detect changes in the contents of files and also in
98 // their mode.
99 //
100 // Please note that the hash is calculated on first invocation of Hash(),
101 // meaning that it will not update when the underlying file changes
102 // between invocations.
103 //
104 // The hash of a directory is always a 24-bytes slice of zero values
105 func (n *node) Hash() []byte {
106 if n.hash == nil {
107 n.calculateHash()
108 }
109 return n.hash
110 }
111
112 func (n *node) Name() string {
113 return path.Base(n.path)
114 }
115
116 func (n *node) IsDir() bool {
117 return n.isDir
118 }
119
120 func (n *node) Skip() bool {
121 return false
122 }
123
124 func (n *node) Children() ([]noder.Noder, error) {
125 if err := n.calculateChildren(); err != nil {
126 return nil, err
127 }
128
129 return n.children, nil
130 }
131
132 func (n *node) NumChildren() (int, error) {
133 if err := n.calculateChildren(); err != nil {
134 return -1, err
135 }
136
137 return len(n.children), nil
138 }
139
140 func (n *node) calculateChildren() error {
141 if !n.IsDir() {
142 return nil
143 }
144
145 if len(n.children) != 0 {
146 return nil
147 }
148
149 files, err := n.fs.ReadDir(n.path)
150 if err != nil {
151 if os.IsNotExist(err) {
152 return nil
153 }
154 return err
155 }
156
157 for _, file := range files {
158 if _, ok := ignore[file.Name()]; ok {
159 continue
160 }
161
162 if file.Mode()&os.ModeSocket != 0 {
163 continue
164 }
165
166 c, err := n.newChildNode(file)
167 if err != nil {
168 return err
169 }
170
171 n.children = append(n.children, c)
172 }
173
174 return nil
175 }
176
177 func (n *node) newChildNode(file os.FileInfo) (*node, error) {
178 path := path.Join(n.path, file.Name())
179
180 node := &node{
181 fs: n.fs,
182 submodules: n.submodules,
183 idx: n.idx,
184 idxMap: n.idxMap,
185
186 path: path,
187 isDir: file.IsDir(),
188 size: file.Size(),
189 mode: file.Mode(),
190 modTime: file.ModTime(),
191 }
192
193 if _, isSubmodule := n.submodules[path]; isSubmodule {
194 node.isDir = false
195 }
196
197 return node, nil
198 }
199
200 func (n *node) calculateHash() {
201 if n.isDir {
202 n.hash = make([]byte, 24)
203 return
204 }
205 mode, err := filemode.NewFromOSFileMode(n.mode)
206 if err != nil {
207 n.hash = plumbing.ZeroHash[:]
208 return
209 }
210 if submoduleHash, isSubmodule := n.submodules[n.path]; isSubmodule {
211 n.hash = append(submoduleHash[:], filemode.Submodule.Bytes()...)
212 return
213 }
214
215 if n.idxMap != nil {
216 if entry, ok := n.idxMap[n.path]; ok {
217 if n.metadataMatches(entry) {
218 n.hash = append(entry.Hash[:], mode.Bytes()...)
219 return
220 }
221 }
222 }
223
224 var hash plumbing.Hash
225 if n.mode&os.ModeSymlink != 0 {
226 hash = n.doCalculateHashForSymlink()
227 } else {
228 hash = n.doCalculateHashForRegular()
229 }
230 n.hash = append(hash[:], mode.Bytes()...)
231 }
232
233 func (n *node) metadataMatches(entry *index.Entry) bool {
234 if entry == nil {
235 return false
236 }
237
238 if uint32(n.size) != entry.Size {
239 return false
240 }
241
242 if !n.modTime.IsZero() && !n.modTime.Equal(entry.ModifiedAt) {
243 return false
244 }
245
246 mode, err := filemode.NewFromOSFileMode(n.mode)
247 if err != nil {
248 return false
249 }
250
251 if mode != entry.Mode {
252 return false
253 }
254
255 if n.idx != nil && !n.idx.ModTime.IsZero() && !n.modTime.IsZero() {
256 if !n.modTime.Before(n.idx.ModTime) {
257 return false
258 }
259 }
260
261 // If we couldn't perform the racy git check (idx is nil or idx.ModTime is zero),
262 // we cannot safely rely on metadata alone — force content hashing.
263 // This can occur with in-memory storage where the index file timestamp is unavailable.
264 if n.idx == nil || n.idx.ModTime.IsZero() {
265 return false
266 }
267
268 return true
269 }
270
271 func (n *node) doCalculateHashForRegular() plumbing.Hash {
272 f, err := n.fs.Open(n.path)
273 if err != nil {
274 return plumbing.ZeroHash
275 }
276
277 defer f.Close()
278
279 h := plumbing.NewHasher(plumbing.BlobObject, n.size)
280 if _, err := io.Copy(h, f); err != nil {
281 return plumbing.ZeroHash
282 }
283
284 return h.Sum()
285 }
286
287 func (n *node) doCalculateHashForSymlink() plumbing.Hash {
288 target, err := n.fs.Readlink(n.path)
289 if err != nil {
290 return plumbing.ZeroHash
291 }
292
293 h := plumbing.NewHasher(plumbing.BlobObject, n.size)
294 if _, err := h.Write([]byte(target)); err != nil {
295 return plumbing.ZeroHash
296 }
297
298 return h.Sum()
299 }
300
301 func (n *node) String() string {
302 return n.path
303 }