Debian Codegraph @

plumbing/object/tree.go

raw
1 package object
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "path"
9 "path/filepath"
10 "sort"
11 "strings"
12
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/storer"
17 "github.com/go-git/go-git/v5/utils/ioutil"
18 "github.com/go-git/go-git/v5/utils/sync"
19 )
20
21 const (
22 maxTreeDepth = 1024
23 startingStackSize = 8
24 )
25
26 // New errors defined by this package.
27 var (
28 ErrMaxTreeDepth = errors.New("maximum tree depth exceeded")
29 ErrFileNotFound = errors.New("file not found")
30 ErrDirectoryNotFound = errors.New("directory not found")
31 ErrEntryNotFound = errors.New("entry not found")
32 ErrEntriesNotSorted = errors.New("entries in tree are not sorted")
33 ErrMalformedTree = errors.New("malformed tree")
34 )
35
36 // Tree is basically like a directory - it references a bunch of other trees
37 // and/or blobs (i.e. files and sub-directories)
38 type Tree struct {
39 Entries []TreeEntry
40 Hash plumbing.Hash
41
42 s storer.EncodedObjectStorer
43 t map[string]*Tree // tree path cache
44 entriesSorted bool
45 }
46
47 // GetTree gets a tree from an object storer and decodes it.
48 func GetTree(s storer.EncodedObjectStorer, h plumbing.Hash) (*Tree, error) {
49 o, err := s.EncodedObject(plumbing.TreeObject, h)
50 if err != nil {
51 return nil, err
52 }
53
54 return DecodeTree(s, o)
55 }
56
57 // DecodeTree decodes an encoded object into a *Tree and associates it to the
58 // given object storer.
59 func DecodeTree(s storer.EncodedObjectStorer, o plumbing.EncodedObject) (*Tree, error) {
60 t := &Tree{s: s}
61 if err := t.Decode(o); err != nil {
62 return nil, err
63 }
64
65 return t, nil
66 }
67
68 // TreeEntry represents a file
69 type TreeEntry struct {
70 Name string
71 Mode filemode.FileMode
72 Hash plumbing.Hash
73 }
74
75 // File returns the hash of the file identified by the `path` argument.
76 // The path is interpreted as relative to the tree receiver.
77 func (t *Tree) File(path string) (*File, error) {
78 e, err := t.FindEntry(path)
79 if err != nil {
80 return nil, ErrFileNotFound
81 }
82
83 blob, err := GetBlob(t.s, e.Hash)
84 if err != nil {
85 if err == plumbing.ErrObjectNotFound {
86 return nil, ErrFileNotFound
87 }
88 return nil, err
89 }
90
91 return NewFile(path, e.Mode, blob), nil
92 }
93
94 // Size returns the plaintext size of an object, without reading it
95 // into memory.
96 func (t *Tree) Size(path string) (int64, error) {
97 e, err := t.FindEntry(path)
98 if err != nil {
99 return 0, ErrEntryNotFound
100 }
101
102 return t.s.EncodedObjectSize(e.Hash)
103 }
104
105 // Tree returns the tree identified by the `path` argument.
106 // The path is interpreted as relative to the tree receiver.
107 func (t *Tree) Tree(path string) (*Tree, error) {
108 e, err := t.FindEntry(path)
109 if err != nil {
110 return nil, ErrDirectoryNotFound
111 }
112
113 tree, err := GetTree(t.s, e.Hash)
114 if err == plumbing.ErrObjectNotFound {
115 return nil, ErrDirectoryNotFound
116 }
117
118 return tree, err
119 }
120
121 // TreeEntryFile returns the *File for a given *TreeEntry.
122 //
123 // The entry's name is validated against pathutil.ValidTreePath for
124 // the same reason FindEntry validates: TreeEntryFile is a boundary
125 // where attacker-controlled tree data leaves the trusted store as a
126 // *File whose Name a caller can hand to filesystem ops.
127 func (t *Tree) TreeEntryFile(e *TreeEntry) (*File, error) {
128 if err := pathutil.ValidTreePath(e.Name); err != nil {
129 return nil, err
130 }
131
132 blob, err := GetBlob(t.s, e.Hash)
133 if err != nil {
134 return nil, err
135 }
136
137 return NewFile(e.Name, e.Mode, blob), nil
138 }
139
140 // FindEntry search a TreeEntry in this tree or any subtree.
141 //
142 // The lookup path is validated against pathutil.ValidTreePath to
143 // prevent attacker-controlled tree contents from leaking past this
144 // boundary as `.git`-shaped or path-traversal-shaped names. Callers
145 // that legitimately need to look up unsafe paths should walk the
146 // tree manually.
147 func (t *Tree) FindEntry(path string) (*TreeEntry, error) {
148 if err := pathutil.ValidTreePath(path); err != nil {
149 return nil, err
150 }
151 if t.t == nil {
152 t.t = make(map[string]*Tree)
153 }
154
155 pathParts := strings.Split(path, "/")
156 startingTree := t
157 pathCurrent := ""
158
159 // search for the longest path in the tree path cache
160 for i := len(pathParts) - 1; i > 1; i-- {
161 path := filepath.Join(pathParts[:i]...)
162
163 tree, ok := t.t[path]
164 if ok {
165 startingTree = tree
166 pathParts = pathParts[i:]
167 pathCurrent = path
168
169 break
170 }
171 }
172
173 var tree *Tree
174 var err error
175 for tree = startingTree; len(pathParts) > 1; pathParts = pathParts[1:] {
176 if tree, err = tree.dir(pathParts[0]); err != nil {
177 return nil, err
178 }
179
180 pathCurrent = filepath.Join(pathCurrent, pathParts[0])
181 t.t[pathCurrent] = tree
182 }
183
184 return tree.entry(pathParts[0])
185 }
186
187 func (t *Tree) dir(baseName string) (*Tree, error) {
188 entry, err := t.entry(baseName)
189 if err != nil {
190 return nil, ErrDirectoryNotFound
191 }
192
193 obj, err := t.s.EncodedObject(plumbing.TreeObject, entry.Hash)
194 if err != nil {
195 return nil, err
196 }
197
198 tree := &Tree{s: t.s}
199 err = tree.Decode(obj)
200
201 return tree, err
202 }
203
204 func (t *Tree) entry(baseName string) (*TreeEntry, error) {
205 if t.entriesSorted {
206 if entry := t.searchEntry(baseName); entry != nil {
207 return entry, nil
208 }
209 return nil, ErrEntryNotFound
210 }
211
212 pastName := baseName + "/"
213 for i := range t.Entries {
214 entry := &t.Entries[i]
215 if entry.Name == baseName {
216 return entry, nil
217 }
218 if treeEntrySortName(entry) > pastName {
219 break
220 }
221 }
222
223 return nil, ErrEntryNotFound
224 }
225
226 func (t *Tree) searchEntry(baseName string) *TreeEntry {
227 if i := t.searchEntryIndex(baseName); i < len(t.Entries) && t.Entries[i].Name == baseName {
228 return &t.Entries[i]
229 }
230
231 if i := t.searchEntryIndex(baseName + "/"); i < len(t.Entries) && t.Entries[i].Name == baseName {
232 return &t.Entries[i]
233 }
234
235 return nil
236 }
237
238 func (t *Tree) searchEntryIndex(name string) int {
239 return sort.Search(len(t.Entries), func(i int) bool {
240 return treeEntrySortName(&t.Entries[i]) >= name
241 })
242 }
243
244 // Files returns a FileIter allowing to iterate over the Tree
245 func (t *Tree) Files() *FileIter {
246 return NewFileIter(t.s, t)
247 }
248
249 // ID returns the object ID of the tree. The returned value will always match
250 // the current value of Tree.Hash.
251 //
252 // ID is present to fulfill the Object interface.
253 func (t *Tree) ID() plumbing.Hash {
254 return t.Hash
255 }
256
257 // Type returns the type of object. It always returns plumbing.TreeObject.
258 func (t *Tree) Type() plumbing.ObjectType {
259 return plumbing.TreeObject
260 }
261
262 func (t *Tree) reset() {
263 storer := t.s
264 *t = Tree{s: storer}
265 }
266
267 // Decode transform an plumbing.EncodedObject into a Tree struct
268 func (t *Tree) Decode(o plumbing.EncodedObject) (err error) {
269 if o.Type() != plumbing.TreeObject {
270 return ErrUnsupportedObject
271 }
272
273 t.reset()
274 t.Hash = o.Hash()
275 // assume tree is sorted as a valid tree should always be sorted.
276 t.entriesSorted = true
277 if o.Size() == 0 {
278 return nil
279 }
280
281 reader, err := o.Reader()
282 if err != nil {
283 return err
284 }
285 defer ioutil.CheckClose(reader, &err)
286
287 r := sync.GetBufioReader(reader)
288 defer sync.PutBufioReader(r)
289
290 var prevSortName string
291 for {
292 str, err := r.ReadString(' ')
293 if err != nil {
294 if err == io.EOF {
295 if len(str) != 0 {
296 return fmt.Errorf("%w: missing mode terminator", ErrMalformedTree)
297 }
298 break
299 }
300
301 return err
302 }
303 str = str[:len(str)-1] // strip last byte (' ')
304
305 mode, err := filemode.New(str)
306 if err != nil {
307 return fmt.Errorf("%w: malformed mode", ErrMalformedTree)
308 }
309 mode = canonicalTreeMode(mode)
310
311 name, err := r.ReadString(0)
312 if err != nil {
313 if err == io.EOF {
314 return fmt.Errorf("%w: missing filename terminator", ErrMalformedTree)
315 }
316 return err
317 }
318 if len(name) == 1 {
319 return fmt.Errorf("%w: empty filename", ErrMalformedTree)
320 }
321
322 var hash plumbing.Hash
323 if _, err = io.ReadFull(r, hash[:]); err != nil {
324 if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
325 return fmt.Errorf("%w: truncated object id", ErrMalformedTree)
326 }
327 return err
328 }
329
330 baseName := name[:len(name)-1]
331 entry := TreeEntry{
332 Hash: hash,
333 Mode: mode,
334 Name: baseName,
335 }
336 sortName := treeEntrySortName(&entry)
337 if len(t.Entries) != 0 && prevSortName > sortName {
338 t.entriesSorted = false
339 }
340 prevSortName = sortName
341 t.Entries = append(t.Entries, entry)
342 }
343
344 return nil
345 }
346
347 type TreeEntrySorter []TreeEntry
348
349 func (s TreeEntrySorter) Len() int {
350 return len(s)
351 }
352
353 func (s TreeEntrySorter) Less(i, j int) bool {
354 return treeEntrySortName(&s[i]) < treeEntrySortName(&s[j])
355 }
356
357 func (s TreeEntrySorter) Swap(i, j int) {
358 s[i], s[j] = s[j], s[i]
359 }
360
361 // Git compares tree entries as if directory names had a trailing slash.
362 func treeEntrySortName(e *TreeEntry) string {
363 if e.Mode == filemode.Dir {
364 return e.Name + "/"
365 }
366 return e.Name
367 }
368
369 func canonicalTreeMode(mode filemode.FileMode) filemode.FileMode {
370 switch mode & 0o170000 {
371 case 0o040000:
372 return filemode.Dir
373 case 0o100000:
374 if mode&0o111 != 0 {
375 return filemode.Executable
376 }
377 return filemode.Regular
378 case 0o120000:
379 return filemode.Symlink
380 default:
381 return filemode.Submodule
382 }
383 }
384
385 // Encode transforms a Tree into a plumbing.EncodedObject.
386 // The tree entries must be sorted by name.
387 func (t *Tree) Encode(o plumbing.EncodedObject) (err error) {
388 o.SetType(plumbing.TreeObject)
389 w, err := o.Writer()
390 if err != nil {
391 return err
392 }
393
394 defer ioutil.CheckClose(w, &err)
395
396 if !sort.IsSorted(TreeEntrySorter(t.Entries)) {
397 return ErrEntriesNotSorted
398 }
399
400 for _, entry := range t.Entries {
401 if strings.IndexByte(entry.Name, 0) != -1 {
402 return fmt.Errorf("malformed filename %q", entry.Name)
403 }
404 if _, err = fmt.Fprintf(w, "%o %s", entry.Mode, entry.Name); err != nil {
405 return err
406 }
407
408 if _, err = w.Write([]byte{0x00}); err != nil {
409 return err
410 }
411
412 if _, err = w.Write(entry.Hash[:]); err != nil {
413 return err
414 }
415 }
416
417 return err
418 }
419
420 // Diff returns a list of changes between this tree and the provided one
421 func (t *Tree) Diff(to *Tree) (Changes, error) {
422 return t.DiffContext(context.Background(), to)
423 }
424
425 // DiffContext returns a list of changes between this tree and the provided one
426 // Error will be returned if context expires. Provided context must be non nil.
427 //
428 // NOTE: Since version 5.1.0 the renames are correctly handled, the settings
429 // used are the recommended options DefaultDiffTreeOptions.
430 func (t *Tree) DiffContext(ctx context.Context, to *Tree) (Changes, error) {
431 return DiffTreeWithOptions(ctx, t, to, DefaultDiffTreeOptions)
432 }
433
434 // Patch returns a slice of Patch objects with all the changes between trees
435 // in chunks. This representation can be used to create several diff outputs.
436 func (t *Tree) Patch(to *Tree) (*Patch, error) {
437 return t.PatchContext(context.Background(), to)
438 }
439
440 // PatchContext returns a slice of Patch objects with all the changes between
441 // trees in chunks. This representation can be used to create several diff
442 // outputs. If context expires, an error will be returned. Provided context must
443 // be non-nil.
444 //
445 // NOTE: Since version 5.1.0 the renames are correctly handled, the settings
446 // used are the recommended options DefaultDiffTreeOptions.
447 func (t *Tree) PatchContext(ctx context.Context, to *Tree) (*Patch, error) {
448 changes, err := t.DiffContext(ctx, to)
449 if err != nil {
450 return nil, err
451 }
452
453 return changes.PatchContext(ctx)
454 }
455
456 // treeEntryIter facilitates iterating through the TreeEntry objects in a Tree.
457 type treeEntryIter struct {
458 t *Tree
459 pos int
460 }
461
462 func (iter *treeEntryIter) Next() (TreeEntry, error) {
463 if iter.pos >= len(iter.t.Entries) {
464 return TreeEntry{}, io.EOF
465 }
466 iter.pos++
467 return iter.t.Entries[iter.pos-1], nil
468 }
469
470 // TreeWalker provides a means of walking through all of the entries in a Tree.
471 type TreeWalker struct {
472 stack []*treeEntryIter
473 base string
474 recursive bool
475 seen map[plumbing.Hash]bool
476
477 s storer.EncodedObjectStorer
478 t *Tree
479 }
480
481 // NewTreeWalker returns a new TreeWalker for the given tree.
482 //
483 // It is the caller's responsibility to call Close() when finished with the
484 // tree walker.
485 func NewTreeWalker(t *Tree, recursive bool, seen map[plumbing.Hash]bool) *TreeWalker {
486 stack := make([]*treeEntryIter, 0, startingStackSize)
487 stack = append(stack, &treeEntryIter{t, 0})
488
489 return &TreeWalker{
490 stack: stack,
491 recursive: recursive,
492 seen: seen,
493
494 s: t.s,
495 t: t,
496 }
497 }
498
499 // Next returns the next object from the tree. Objects are returned in order
500 // and subtrees are included. After the last object has been returned further
501 // calls to Next() will return io.EOF.
502 //
503 // In the current implementation any objects which cannot be found in the
504 // underlying repository will be skipped automatically. It is possible that this
505 // may change in future versions.
506 func (w *TreeWalker) Next() (name string, entry TreeEntry, err error) {
507 var obj *Tree
508 for {
509 current := len(w.stack) - 1
510 if current < 0 {
511 // Nothing left on the stack so we're finished
512 err = io.EOF
513 return
514 }
515
516 if current > maxTreeDepth {
517 // We're probably following bad data or some self-referencing tree
518 err = ErrMaxTreeDepth
519 return
520 }
521
522 entry, err = w.stack[current].Next()
523 if err == io.EOF {
524 // Finished with the current tree, move back up to the parent
525 w.stack = w.stack[:current]
526 w.base, _ = path.Split(w.base)
527 w.base = strings.TrimSuffix(w.base, "/")
528 continue
529 }
530
531 if err != nil {
532 return
533 }
534
535 if w.seen[entry.Hash] {
536 continue
537 }
538
539 if err := pathutil.ValidTreePath(entry.Name); err != nil {
540 return name, entry, err
541 }
542
543 if entry.Mode == filemode.Dir {
544 obj, err = GetTree(w.s, entry.Hash)
545 }
546
547 name = simpleJoin(w.base, entry.Name)
548
549 if err != nil {
550 err = io.EOF
551 return
552 }
553
554 break
555 }
556
557 if !w.recursive {
558 return
559 }
560
561 if obj != nil {
562 w.stack = append(w.stack, &treeEntryIter{obj, 0})
563 w.base = simpleJoin(w.base, entry.Name)
564 }
565
566 return
567 }
568
569 // Tree returns the tree that the tree walker most recently operated on.
570 func (w *TreeWalker) Tree() *Tree {
571 current := len(w.stack) - 1
572 if w.stack[current].pos == 0 {
573 current--
574 }
575
576 if current < 0 {
577 return nil
578 }
579
580 return w.stack[current].t
581 }
582
583 // Close releases any resources used by the TreeWalker.
584 func (w *TreeWalker) Close() {
585 w.stack = nil
586 }
587
588 // TreeIter provides an iterator for a set of trees.
589 type TreeIter struct {
590 storer.EncodedObjectIter
591 s storer.EncodedObjectStorer
592 }
593
594 // NewTreeIter takes a storer.EncodedObjectStorer and a
595 // storer.EncodedObjectIter and returns a *TreeIter that iterates over all
596 // tree contained in the storer.EncodedObjectIter.
597 //
598 // Any non-tree object returned by the storer.EncodedObjectIter is skipped.
599 func NewTreeIter(s storer.EncodedObjectStorer, iter storer.EncodedObjectIter) *TreeIter {
600 return &TreeIter{iter, s}
601 }
602
603 // Next moves the iterator to the next tree and returns a pointer to it. If
604 // there are no more trees, it returns io.EOF.
605 func (iter *TreeIter) Next() (*Tree, error) {
606 for {
607 obj, err := iter.EncodedObjectIter.Next()
608 if err != nil {
609 return nil, err
610 }
611
612 if obj.Type() != plumbing.TreeObject {
613 continue
614 }
615
616 return DecodeTree(iter.s, obj)
617 }
618 }
619
620 // ForEach call the cb function for each tree contained on this iter until
621 // an error happens or the end of the iter is reached. If ErrStop is sent
622 // the iteration is stop but no error is returned. The iterator is closed.
623 func (iter *TreeIter) ForEach(cb func(*Tree) error) error {
624 return iter.EncodedObjectIter.ForEach(func(obj plumbing.EncodedObject) error {
625 if obj.Type() != plumbing.TreeObject {
626 return nil
627 }
628
629 t, err := DecodeTree(iter.s, obj)
630 if err != nil {
631 return err
632 }
633
634 return cb(t)
635 })
636 }
637
638 func simpleJoin(parent, child string) string {
639 if len(parent) > 0 {
640 return parent + "/" + child
641 }
642 return child
643 }