Debian Codegraph @

tree.go

raw
1 package gitobj
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "hash"
8 "io"
9 "sort"
10 "strconv"
11 "strings"
12
13 "github.com/git-lfs/gitobj/v2/pack"
14 )
15
16 // We define these here instead of using the system ones because not all
17 // operating systems use the traditional values. For example, zOS uses
18 // different values.
19 const (
20 sIFMT = int32(0170000)
21 sIFREG = int32(0100000)
22 sIFDIR = int32(0040000)
23 sIFLNK = int32(0120000)
24 sIFGITLINK = int32(0160000)
25 )
26
27 // Tree encapsulates a Git tree object.
28 type Tree struct {
29 // Entries is the list of entries held by this tree.
30 Entries []*TreeEntry
31 }
32
33 // Type implements Object.ObjectType by returning the correct object type for
34 // Trees, TreeObjectType.
35 func (t *Tree) Type() ObjectType { return TreeObjectType }
36
37 // Decode implements Object.Decode and decodes the uncompressed tree being
38 // read. It returns the number of uncompressed bytes being consumed off of the
39 // stream, which should be strictly equal to the size given.
40 //
41 // If any error was encountered along the way, that will be returned, along with
42 // the number of bytes read up to that point.
43 func (t *Tree) Decode(hash hash.Hash, from io.Reader, size int64) (n int, err error) {
44 hashlen := hash.Size()
45 buf := bufio.NewReader(from)
46
47 var entries []*TreeEntry
48 for {
49 modes, err := buf.ReadString(' ')
50 if err != nil {
51 if err == io.EOF {
52 break
53 }
54 return n, err
55 }
56 n += len(modes)
57 modes = strings.TrimSuffix(modes, " ")
58
59 mode, _ := strconv.ParseInt(modes, 8, 32)
60
61 fname, err := buf.ReadString('\x00')
62 if err != nil {
63 return n, err
64 }
65 n += len(fname)
66 fname = strings.TrimSuffix(fname, "\x00")
67
68 var sha [pack.MaxHashSize]byte
69 if _, err = io.ReadFull(buf, sha[:hashlen]); err != nil {
70 return n, err
71 }
72 n += hashlen
73
74 entries = append(entries, &TreeEntry{
75 Name: fname,
76 Oid: sha[:hashlen],
77 Filemode: int32(mode),
78 })
79 }
80
81 t.Entries = entries
82
83 return n, nil
84 }
85
86 // Encode encodes the tree's contents to the given io.Writer, "w". If there was
87 // any error copying the tree's contents, that error will be returned.
88 //
89 // Otherwise, the number of bytes written will be returned.
90 func (t *Tree) Encode(to io.Writer) (n int, err error) {
91 const entryTmpl = "%s %s\x00%s"
92
93 for _, entry := range t.Entries {
94 fmode := strconv.FormatInt(int64(entry.Filemode), 8)
95
96 ne, err := fmt.Fprintf(to, entryTmpl,
97 fmode,
98 entry.Name,
99 entry.Oid)
100
101 if err != nil {
102 return n, err
103 }
104
105 n = n + ne
106 }
107 return
108 }
109
110 // Merge performs a merge operation against the given set of `*TreeEntry`'s by
111 // either replacing existing tree entries of the same name, or appending new
112 // entries in sub-tree order.
113 //
114 // It returns a copy of the tree, and performs the merge in O(n*log(n)) time.
115 func (t *Tree) Merge(others ...*TreeEntry) *Tree {
116 unseen := make(map[string]*TreeEntry)
117
118 // Build a cache of name to *TreeEntry.
119 for _, other := range others {
120 unseen[other.Name] = other
121 }
122
123 // Map the existing entries ("t.Entries") into a new set by either
124 // copying an existing entry, or replacing it with a new one.
125 entries := make([]*TreeEntry, 0, len(t.Entries))
126 for _, entry := range t.Entries {
127 if other, ok := unseen[entry.Name]; ok {
128 entries = append(entries, other)
129 delete(unseen, entry.Name)
130 } else {
131 oid := make([]byte, len(entry.Oid))
132 copy(oid, entry.Oid)
133
134 entries = append(entries, &TreeEntry{
135 Filemode: entry.Filemode,
136 Name: entry.Name,
137 Oid: oid,
138 })
139 }
140 }
141
142 // For all the items we haven't replaced into the new set, append them
143 // to the entries.
144 for _, remaining := range unseen {
145 entries = append(entries, remaining)
146 }
147
148 // Call sort afterwords, as a tradeoff between speed and spacial
149 // complexity. As a future point of optimization, adding new elements
150 // (see: above) could be done as a linear pass of the "entries" set.
151 //
152 // In order to do that, we must have a constant-time lookup of both
153 // entries in the existing and new sets. This requires building a
154 // map[string]*TreeEntry for the given "others" as well as "t.Entries".
155 //
156 // Trees can be potentially large, so trade this spacial complexity for
157 // an O(n*log(n)) sort.
158 sort.Sort(SubtreeOrder(entries))
159
160 return &Tree{Entries: entries}
161 }
162
163 // Equal returns whether the receiving and given trees are equal, or in other
164 // words, whether they are represented by the same SHA-1 when saved to the
165 // object database.
166 func (t *Tree) Equal(other *Tree) bool {
167 if (t == nil) != (other == nil) {
168 return false
169 }
170
171 if t != nil {
172 if len(t.Entries) != len(other.Entries) {
173 return false
174 }
175
176 for i := 0; i < len(t.Entries); i++ {
177 e1 := t.Entries[i]
178 e2 := other.Entries[i]
179
180 if !e1.Equal(e2) {
181 return false
182 }
183 }
184 }
185 return true
186 }
187
188 // TreeEntry encapsulates information about a single tree entry in a tree
189 // listing.
190 type TreeEntry struct {
191 // Name is the entry name relative to the tree in which this entry is
192 // contained.
193 Name string
194 // Oid is the object ID for this tree entry.
195 Oid []byte
196 // Filemode is the filemode of this tree entry on disk.
197 Filemode int32
198 }
199
200 // Equal returns whether the receiving and given TreeEntry instances are
201 // identical in name, filemode, and OID.
202 func (e *TreeEntry) Equal(other *TreeEntry) bool {
203 if (e == nil) != (other == nil) {
204 return false
205 }
206
207 if e != nil {
208 return e.Name == other.Name &&
209 bytes.Equal(e.Oid, other.Oid) &&
210 e.Filemode == other.Filemode
211 }
212 return true
213 }
214
215 // Type is the type of entry (either blob: BlobObjectType, or a sub-tree:
216 // TreeObjectType).
217 func (e *TreeEntry) Type() ObjectType {
218 switch e.Filemode & sIFMT {
219 case sIFREG:
220 return BlobObjectType
221 case sIFDIR:
222 return TreeObjectType
223 case sIFLNK:
224 return BlobObjectType
225 case sIFGITLINK:
226 return CommitObjectType
227 default:
228 panic(fmt.Sprintf("gitobj: unknown object type: %o",
229 e.Filemode))
230 }
231 }
232
233 // IsLink returns true if the given TreeEntry is a blob which represents a
234 // symbolic link (i.e., with a filemode of 0120000.
235 func (e *TreeEntry) IsLink() bool {
236 return e.Filemode & sIFMT == sIFLNK
237 }
238
239 // SubtreeOrder is an implementation of sort.Interface that sorts a set of
240 // `*TreeEntry`'s according to "subtree" order. This ordering is required to
241 // write trees in a correct, readable format to the Git object database.
242 //
243 // The format is as follows: entries are sorted lexicographically in byte-order,
244 // with subtrees (entries of Type() == gitobj.TreeObjectType) being sorted as
245 // if their `Name` fields ended in a "/".
246 //
247 // See: https://github.com/git/git/blob/v2.13.0/fsck.c#L492-L525 for more
248 // details.
249 type SubtreeOrder []*TreeEntry
250
251 // Len implements sort.Interface.Len() and return the length of the underlying
252 // slice.
253 func (s SubtreeOrder) Len() int { return len(s) }
254
255 // Swap implements sort.Interface.Swap() and swaps the two elements at i and j.
256 func (s SubtreeOrder) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
257
258 // Less implements sort.Interface.Less() and returns whether the element at "i"
259 // is compared as "less" than the element at "j". In other words, it returns if
260 // the element at "i" should be sorted ahead of that at "j".
261 //
262 // It performs this comparison in lexicographic byte-order according to the
263 // rules above (see SubtreeOrder).
264 func (s SubtreeOrder) Less(i, j int) bool {
265 return s.Name(i) < s.Name(j)
266 }
267
268 // Name returns the name for a given entry indexed at "i", which is a C-style
269 // string ('\0' terminated unless it's a subtree), optionally terminated with
270 // '/' if it's a subtree.
271 //
272 // This is done because '/' sorts ahead of '\0', and is compatible with the
273 // tree order in upstream Git.
274 func (s SubtreeOrder) Name(i int) string {
275 if i < 0 || i >= len(s) {
276 return ""
277 }
278
279 entry := s[i]
280 if entry == nil {
281 return ""
282 }
283
284 if entry.Type() == TreeObjectType {
285 return entry.Name + "/"
286 }
287 return entry.Name + "\x00"
288 }