gunk-dev/the-valley

tree.go

sourcedfa994caaeb3main's published tip history
12.4 KiB
1package delta
2
3// Between reads two trees straight from git's object store, with
4// `git cat-file`, and nothing else: no checkout, no filters, no attributes,
5// no diff drivers, no rename detection, and no replacement refs.
6
7import (
8 "bufio"
9 "bytes"
10 "crypto/sha256"
11 "encoding/hex"
12 "errors"
13 "fmt"
14 "io"
15 "os/exec"
16 "sort"
17 "strconv"
18 "strings"
19)
20
21// Repo is a git repository Between reads, and how git is run to read it.
22type Repo struct {
23 Git string // the git program; "git" on PATH when empty
24 Dir string // the repository's directory; the current one when empty
25 Env []string // git's environment; this process's when nil
26}
27
28// modeTree is a subtree's mode as git writes it in a tree.
29const modeTree = "40000"
30
31// Between is the delta from the tree pre to the tree post. Each is named
32// by the full object ID of a tree, or of a commit, which stands for its
33// tree.
34//
35// Both trees are read whole, and either is refused when a checkout on
36// case-sensitive Linux could not hold it faithfully: an entry whose mode
37// is not 100644, 100755, 120000 or a subtree's (a submodule among them);
38// a name that is empty, . or .., .git in any case, holds a slash, or is
39// longer than Linux's limit of 255 bytes; two entries with one name, as a
40// file and a directory at one path are; a subtree with no entries, which
41// a checkout drops; entries out of git's order; an entry whose object is
42// not the type its mode says; and a symlink whose target is empty, holds
43// a NUL, or is longer than Linux's limit of 4095 bytes. Every entry of
44// both trees is checked, the ones the delta leaves out included.
45func Between(r Repo, pre, post string) (Delta, error) {
46 rd, err := r.open()
47 if err != nil {
48 return nil, err
49 }
50 defer rd.close()
51 var trees [2]string
52 for i, oid := range []string{pre, post} {
53 if trees[i], err = rd.treeOf(oid); err != nil {
54 return nil, err
55 }
56 if err := rd.check(trees[i], ""); err != nil {
57 return nil, err
58 }
59 }
60 if err := rd.checkLeaves(); err != nil {
61 return nil, err
62 }
63 var d Delta
64 if err := rd.diff(trees[0], trees[1], "", &d); err != nil {
65 return nil, err
66 }
67 sort.Slice(d, func(i, j int) bool { return d[i].Path < d[j].Path })
68 return d, nil
69}
70
71// treeEntry is one entry of a tree object.
72type treeEntry struct {
73 mode, name, oid string
74}
75
76// reader holds one `git cat-file --batch` open, and what it has read.
77type reader struct {
78 repo Repo
79 cmd *exec.Cmd
80 in io.WriteCloser
81 out *bufio.Reader
82 hexLen int // an object ID's length in hex, once known
83 trees map[string][]treeEntry // tree → its entries, each tree checked
84 leaves map[string]string // blob → the mode the first entry naming it gave it
85 links map[string]string // blob → the path of the first symlink whose target it is
86 sums map[string][32]byte // blob → the SHA-256 of its content
87}
88
89// maxTarget is the longest symlink target Linux takes: PATH_MAX, 4096
90// bytes, less the NUL that ends it.
91const maxTarget = 4095
92
93func (r Repo) command(args ...string) *exec.Cmd {
94 program := r.Git
95 if program == "" {
96 program = "git"
97 }
98 cmd := exec.Command(program, append([]string{"--no-replace-objects"}, args...)...)
99 cmd.Dir = r.Dir
100 cmd.Env = r.Env
101 return cmd
102}
103
104func (r Repo) open() (*reader, error) {
105 cmd := r.command("cat-file", "--batch")
106 in, err := cmd.StdinPipe()
107 if err != nil {
108 return nil, err
109 }
110 out, err := cmd.StdoutPipe()
111 if err != nil {
112 return nil, err
113 }
114 if err := cmd.Start(); err != nil {
115 return nil, fmt.Errorf("could not run git cat-file: %v", err)
116 }
117 return &reader{
118 repo: r, cmd: cmd, in: in, out: bufio.NewReader(out),
119 trees: map[string][]treeEntry{}, leaves: map[string]string{}, links: map[string]string{},
120 sums: map[string][32]byte{},
121 }, nil
122}
123
124func (rd *reader) close() {
125 rd.in.Close()
126 io.Copy(io.Discard, rd.out)
127 rd.cmd.Wait()
128}
129
130// validID reports whether oid is a full object ID in lowercase hex, of the
131// repository's length once that is known.
132func (rd *reader) validID(oid string) bool {
133 if rd.hexLen != 0 && len(oid) != rd.hexLen {
134 return false
135 }
136 return (len(oid) == 40 || len(oid) == 64) && lowerHex([]byte(oid))
137}
138
139// read reads one object whole, and its type.
140func (rd *reader) read(oid string) (kind string, data []byte, err error) {
141 if !rd.validID(oid) {
142 return "", nil, fmt.Errorf("%q is not a full object ID", oid)
143 }
144 if _, err := io.WriteString(rd.in, oid+"\n"); err != nil {
145 return "", nil, fmt.Errorf("could not read the object %s: %v", oid, err)
146 }
147 header, err := rd.out.ReadString('\n')
148 if err != nil {
149 return "", nil, fmt.Errorf("could not read the object %s: %v", oid, err)
150 }
151 fields := strings.Fields(header)
152 if len(fields) != 3 || fields[0] != oid {
153 return "", nil, fmt.Errorf("the object %s is not in the repository", oid)
154 }
155 size, err := strconv.ParseInt(fields[2], 10, 64)
156 if err != nil || size < 0 {
157 return "", nil, fmt.Errorf("git gave the size of %s as %q", oid, fields[2])
158 }
159 data = make([]byte, size+1)
160 if _, err := io.ReadFull(rd.out, data); err != nil || data[size] != '\n' {
161 return "", nil, fmt.Errorf("could not read the object %s whole", oid)
162 }
163 rd.hexLen = len(oid)
164 return fields[1], data[:size], nil
165}
166
167// treeOf is the tree an object ID names: the tree itself, or a commit's.
168func (rd *reader) treeOf(oid string) (string, error) {
169 kind, data, err := rd.read(oid)
170 if err != nil {
171 return "", err
172 }
173 switch kind {
174 case "tree":
175 return oid, nil
176 case "commit":
177 line, _, _ := strings.Cut(string(data), "\n")
178 tree, ok := strings.CutPrefix(line, "tree ")
179 if !ok || !rd.validID(tree) {
180 return "", fmt.Errorf("the commit %s does not open with its tree", oid)
181 }
182 return tree, nil
183 }
184 return "", fmt.Errorf("%s is a %s, not a tree or a commit", oid, kind)
185}
186
187// check reads a tree and every subtree under it, and refuses one that a
188// checkout could not hold faithfully, as Between describes. Each tree is
189// read and checked once. Its leaves are kept, for checkLeaves. A tree met
190// again is still refused as an empty directory, since it may have been
191// read first as the empty root, which is no directory.
192func (rd *reader) check(oid, at string) error {
193 entries, done := rd.trees[oid]
194 if !done {
195 kind, data, err := rd.read(oid)
196 if err != nil {
197 return err
198 }
199 if kind != "tree" {
200 return fmt.Errorf("%s is a directory whose object %s is a %s", described(at), oid, kind)
201 }
202 if entries, err = rd.parseTree(data, at); err != nil {
203 return err
204 }
205 }
206 if len(entries) == 0 && at != "" {
207 return fmt.Errorf("%s is an empty directory, which a checkout does not hold", described(at))
208 }
209 if done {
210 return nil
211 }
212 rd.trees[oid] = entries
213 for _, e := range entries {
214 path := join(at, e.name)
215 if e.mode == modeTree {
216 if err := rd.check(e.oid, path); err != nil {
217 return err
218 }
219 continue
220 }
221 if _, seen := rd.leaves[e.oid]; !seen {
222 rd.leaves[e.oid] = e.mode
223 }
224 if _, seen := rd.links[e.oid]; e.mode == ModeSymlink && !seen {
225 rd.links[e.oid] = path
226 }
227 }
228 return nil
229}
230
231// parseTree reads a tree object's entries: "<mode> <name>\0<raw ID>" each.
232func (rd *reader) parseTree(data []byte, at string) ([]treeEntry, error) {
233 size := rd.hexLen / 2
234 var entries []treeEntry
235 names := map[string]bool{}
236 prev := ""
237 for len(data) > 0 {
238 sp := bytes.IndexByte(data, ' ')
239 nul := bytes.IndexByte(data, 0)
240 if sp <= 0 || nul < sp || nul+1+size > len(data) {
241 return nil, fmt.Errorf("the tree at %s is malformed", described(at))
242 }
243 e := treeEntry{mode: string(data[:sp]), name: string(data[sp+1 : nul])}
244 e.oid = hex.EncodeToString(data[nul+1 : nul+1+size])
245 data = data[nul+1+size:]
246 path := join(at, e.name)
247 if err := checkName(e.name); err != nil {
248 return nil, fmt.Errorf("the tree at %s %w", described(at), err)
249 }
250 switch e.mode {
251 case ModeFile, ModeExec, ModeSymlink, modeTree:
252 case "160000":
253 return nil, fmt.Errorf("%s is a submodule, which valley-delta-v1 does not support", described(path))
254 default:
255 return nil, fmt.Errorf("%s has the mode %q, which valley-delta-v1 does not support", described(path), e.mode)
256 }
257 if names[e.name] {
258 return nil, fmt.Errorf("%s is named twice in its tree, as a file and a directory are when they share a path", described(path))
259 }
260 names[e.name] = true
261 // git orders a tree's entries by name, a subtree's read with a
262 // slash after it.
263 key := e.name
264 if e.mode == modeTree {
265 key += "/"
266 }
267 if key <= prev {
268 return nil, fmt.Errorf("the tree at %s holds %q out of git's order", described(at), e.name)
269 }
270 prev = key
271 entries = append(entries, e)
272 }
273 return entries, nil
274}
275
276// checkLeaves refuses an entry whose object is not a blob, or is missing,
277// for every leaf of the trees checked, with one `git cat-file
278// --batch-check`. Then it reads every blob a symlink names, and refuses a
279// target a checkout could not make (checkTarget).
280func (rd *reader) checkLeaves() error {
281 if len(rd.leaves) == 0 {
282 return nil
283 }
284 oids := make([]string, 0, len(rd.leaves))
285 for oid := range rd.leaves {
286 oids = append(oids, oid)
287 }
288 sort.Strings(oids)
289 cmd := rd.repo.command("cat-file", "--batch-check=%(objectname) %(objecttype)")
290 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
291 out, err := cmd.Output()
292 if err != nil {
293 return fmt.Errorf("could not read the trees' entries: %v", err)
294 }
295 lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n")
296 if len(lines) != len(oids) {
297 return errors.New("could not read the trees' entries")
298 }
299 for i, line := range lines {
300 if line != oids[i]+" blob" {
301 return fmt.Errorf("an entry with the mode %s names the object %s, which is no blob in the repository", rd.leaves[oids[i]], oids[i])
302 }
303 }
304 for _, oid := range oids {
305 path, ok := rd.links[oid]
306 if !ok {
307 continue
308 }
309 _, target, err := rd.read(oid)
310 if err != nil {
311 return err
312 }
313 if err := checkTarget(target); err != nil {
314 return fmt.Errorf("the symlink %s %w", described(path), err)
315 }
316 rd.sums[oid] = sha256.Sum256(target)
317 }
318 return nil
319}
320
321// checkTarget refuses a symlink's target that symlink(2) on Linux would
322// not make: an empty one, one holding a NUL, which would end it early,
323// and one longer than maxTarget.
324func checkTarget(target []byte) error {
325 switch {
326 case len(target) == 0:
327 return fmt.Errorf("has an empty target, which a checkout cannot make")
328 case bytes.IndexByte(target, 0) >= 0:
329 return fmt.Errorf("has a target holding a NUL, which a checkout cannot make")
330 case len(target) > maxTarget:
331 return fmt.Errorf("has a target of %d bytes, longer than Linux's limit of %d", len(target), maxTarget)
332 }
333 return nil
334}
335
336// diff adds to d every path under the directory at whose entries differ
337// between the trees pre and post. Either tree may be "", for none. Equal
338// trees hold equal entries, so they are not read again.
339func (rd *reader) diff(pre, post, at string, d *Delta) error {
340 if pre == post {
341 return nil
342 }
343 byName := map[string][2]*treeEntry{}
344 for side, tree := range []string{pre, post} {
345 if tree == "" {
346 continue
347 }
348 for i := range rd.trees[tree] {
349 e := &rd.trees[tree][i]
350 pair := byName[e.name]
351 pair[side] = e
352 byName[e.name] = pair
353 }
354 }
355 for name, pair := range byName {
356 path := join(at, name)
357 var sub [2]string
358 var leaf [2]*treeEntry
359 for side, e := range pair {
360 switch {
361 case e == nil:
362 case e.mode == modeTree:
363 sub[side] = e.oid
364 default:
365 leaf[side] = e
366 }
367 }
368 if sub[0] != "" || sub[1] != "" {
369 if err := rd.diff(sub[0], sub[1], path, d); err != nil {
370 return err
371 }
372 }
373 if leaf[0] == nil && leaf[1] == nil {
374 continue
375 }
376 if leaf[0] != nil && leaf[1] != nil && *leaf[0] == *leaf[1] {
377 continue
378 }
379 c := Change{Path: path}
380 var err error
381 if c.Pre, err = rd.image(leaf[0]); err != nil {
382 return err
383 }
384 if c.Post, err = rd.image(leaf[1]); err != nil {
385 return err
386 }
387 if c.Pre != c.Post {
388 *d = append(*d, c)
389 }
390 }
391 return nil
392}
393
394// image is an entry's image: its mode and the SHA-256 of its blob.
395func (rd *reader) image(e *treeEntry) (Image, error) {
396 if e == nil {
397 return Image{}, nil
398 }
399 sum, ok := rd.sums[e.oid]
400 if !ok {
401 kind, data, err := rd.read(e.oid)
402 if err != nil {
403 return Image{}, err
404 }
405 if kind != "blob" {
406 return Image{}, fmt.Errorf("the object %s is a %s, not a blob", e.oid, kind)
407 }
408 sum = sha256.Sum256(data)
409 rd.sums[e.oid] = sum
410 }
411 return Image{Mode: e.mode, Sum: sum}, nil
412}
413
414func join(at, name string) string {
415 if at == "" {
416 return name
417 }
418 return at + "/" + name
419}
420
421// described names a path in an error: the root, or the path quoted.
422func described(path string) string {
423 if path == "" {
424 return "the root"
425 }
426 return strconv.Quote(path)
427}