github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/tree_gogit.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 // Copyright 2015 The Gogs Authors. All rights reserved. 7 8 //go:build gogit 9 10 package git 11 12 import ( 13 "io" 14 15 "github.com/go-git/go-git/v5/plumbing" 16 "github.com/go-git/go-git/v5/plumbing/object" 17 ) 18 19 // Tree represents a flat directory listing. 20 type Tree struct { 21 ID SHA1 22 ResolvedID SHA1 23 repo *Repository 24 25 gogitTree *object.Tree 26 27 // parent tree 28 ptree *Tree 29 } 30 31 func (t *Tree) loadTreeObject() error { 32 gogitTree, err := t.repo.gogitRepo.TreeObject(t.ID) 33 if err != nil { 34 return err 35 } 36 37 t.gogitTree = gogitTree 38 return nil 39 } 40 41 // ListEntries returns all entries of current tree. 42 func (t *Tree) ListEntries() (Entries, error) { 43 if t.gogitTree == nil { 44 err := t.loadTreeObject() 45 if err != nil { 46 return nil, err 47 } 48 } 49 50 entries := make([]*TreeEntry, len(t.gogitTree.Entries)) 51 for i, entry := range t.gogitTree.Entries { 52 entries[i] = &TreeEntry{ 53 ID: entry.Hash, 54 gogitTreeEntry: &t.gogitTree.Entries[i], 55 ptree: t, 56 } 57 } 58 59 return entries, nil 60 } 61 62 // ListEntriesRecursive returns all entries of current tree recursively including all subtrees 63 func (t *Tree) ListEntriesRecursive() (Entries, error) { 64 if t.gogitTree == nil { 65 err := t.loadTreeObject() 66 if err != nil { 67 return nil, err 68 } 69 } 70 71 var entries []*TreeEntry 72 seen := map[plumbing.Hash]bool{} 73 walker := object.NewTreeWalker(t.gogitTree, true, seen) 74 for { 75 fullName, entry, err := walker.Next() 76 if err == io.EOF { 77 break 78 } 79 if err != nil { 80 return nil, err 81 } 82 if seen[entry.Hash] { 83 continue 84 } 85 86 convertedEntry := &TreeEntry{ 87 ID: entry.Hash, 88 gogitTreeEntry: &entry, 89 ptree: t, 90 fullName: fullName, 91 } 92 entries = append(entries, convertedEntry) 93 } 94 95 return entries, nil 96 }