-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
130 lines (112 loc) · 2.35 KB
/
tree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package git
import (
"errors"
"io/ioutil"
"path"
"strings"
)
var (
ErrNotExist = errors.New("error not exist")
)
type TreeWalkCallback func(string, *TreeEntry) int
// A tree is a flat directory listing.
type Tree struct {
Id sha1
repo *Repository
// parent tree
ptree *Tree
entries Entries
entriesParsed bool
}
// The entries will be traversed in the specified order,
// children subtrees will be automatically loaded as required, and the
// callback will be called once per blob with the current (relative) root
// for the blob and the blob data itself.
//
// If the callback returns a positive value, the passed blob will be skipped
// on the traversal (in pre mode). A negative value stops the walk.
//
// Walk will panic() if an error occurs
func (t *Tree) walk(callback TreeWalkCallback) error {
t._walk(callback, "")
return nil
}
func (t *Tree) _walk(cb TreeWalkCallback, dirname string) bool {
for _, te := range t.ListEntries() {
cont := cb(dirname, te)
switch {
case cont < 0:
return false
case cont == 0:
// descend if it is a tree
if te.Type == ObjectTree {
commit, err := t.repo.getCommit(te.Id)
if err != nil {
panic(err)
}
t, err := t.repo.getTree(commit.Id)
if err != nil {
panic(err)
}
if t._walk(cb, path.Join(dirname, te.name)) == false {
return false
}
}
case cont > 0:
// do nothing, don't descend into the tree
}
}
return true
}
func (t *Tree) SubTree(rpath string) (*Tree, error) {
if len(rpath) == 0 {
return t, nil
}
paths := strings.Split(rpath, "/")
var err error
var g = t
var p = t
var te *TreeEntry
for _, name := range paths {
te, err = p.GetTreeEntryByPath(name)
if err != nil {
return nil, err
}
g, err = t.repo.getTree(te.Id)
if err != nil {
return nil, err
}
g.ptree = p
p = g
}
return g, nil
}
func (t *Tree) ListEntries() Entries {
if t.entriesParsed {
return t.entries
}
t.entriesParsed = true
_, _, dataRc, err := t.repo.getRawObject(t.Id, false)
if err != nil {
return nil
}
defer func() {
dataRc.Close()
}()
// TODO reader
data, err := ioutil.ReadAll(dataRc)
if err != nil {
return nil
}
t.entries, err = parseTreeData(t, data)
if err != nil {
return nil
}
return t.entries
}
func NewTree(repo *Repository, id sha1) *Tree {
tree := new(Tree)
tree.Id = id
tree.repo = repo
return tree
}