gunk-dev/the-valley

tree.go

source826ad0ddebbcmain's published tip history
17.9 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 "context"
11 "crypto/sha256"
12 "encoding/hex"
13 "errors"
14 "fmt"
15 "io"
16 "os/exec"
17 "sort"
18 "strconv"
19 "strings"
20 "time"
21)
22
23// Repo is a git repository Between reads, and how git is run to read it.
24type Repo struct {
25 Git string // the git program; "git" on PATH when empty
26 Dir string // the repository's directory; the current one when empty
27 Env []string // git's environment; this process's when nil
28}
29
30// modeTree is a subtree's mode as git writes it in a tree.
31const modeTree = "40000"
32
33// Between is the delta from the tree pre to the tree post. Each is named
34// by the full object ID of a tree, or of a commit, which stands for its
35// tree.
36//
37// Both trees are read whole, and either is refused when a checkout on
38// case-sensitive Linux could not hold it faithfully: an entry whose mode
39// is not 100644, 100755, 120000 or a subtree's (a submodule among them);
40// a name that is empty, . or .., .git in any case, holds a slash, or is
41// longer than Linux's limit of 255 bytes; two entries with one name, as a
42// file and a directory at one path are; a subtree with no entries, which
43// a checkout drops; entries out of git's order; an entry whose object is
44// not the type its mode says; and a symlink whose target is empty, holds
45// a NUL, or is longer than Linux's limit of 4095 bytes. Every entry of
46// both trees is checked, the ones the delta leaves out included.
47func Between(r Repo, pre, post string) (Delta, error) {
48 return between(r, pre, post, nil)
49}
50
51// Budget is what BetweenWithin may spend reading two trees. Every bound
52// must be set.
53//
54// Bytes bounds the bytes the reading takes in: the content of every tree
55// and blob it reads from git, and every path it builds on the way. Entries
56// bounds the tree entries it visits: each entry once when its tree is read,
57// and once more each time the comparison walks it, so a subtree that two
58// directories name counts twice. Deadline is when the reading must be
59// done. git is killed then, and the reading fails.
60type Budget struct {
61 Bytes int64
62 Entries int64
63 Deadline time.Time
64}
65
66// ErrBudget is wrapped by every error BetweenWithin returns for a bound of
67// its budget, so a caller can tell trees too large to read within the
68// budget from trees that are refused.
69var ErrBudget = errors.New("the budget for reading the trees is spent")
70
71// BetweenWithin is Between held to a budget. It reads what Between reads,
72// refuses what Between refuses, and gives the same delta. It also stops at
73// the first bound it would cross, and returns an error that wraps
74// ErrBudget. An object's type and size are asked for before its content,
75// so git never produces an object that would cross the budget. Between
76// itself is unbounded.
77func BetweenWithin(r Repo, pre, post string, b Budget) (Delta, error) {
78 if b.Bytes <= 0 || b.Entries <= 0 || b.Deadline.IsZero() {
79 return nil, errors.New("a budget bounds bytes, entries and time, and this one leaves one of them unset")
80 }
81 ctx, cancel := context.WithDeadline(context.Background(), b.Deadline)
82 defer cancel()
83 return between(r, pre, post, &limit{budget: b, ctx: ctx})
84}
85
86// between is Between, held to l when l is not nil.
87func between(r Repo, pre, post string, l *limit) (Delta, error) {
88 rd, err := r.open(l)
89 if err != nil {
90 return nil, err
91 }
92 defer rd.close()
93 var trees [2]string
94 for i, oid := range []string{pre, post} {
95 if trees[i], err = rd.treeOf(oid); err != nil {
96 return nil, err
97 }
98 if err := rd.check(trees[i], ""); err != nil {
99 return nil, err
100 }
101 }
102 if err := rd.checkLeaves(); err != nil {
103 return nil, err
104 }
105 var d Delta
106 if err := rd.diff(trees[0], trees[1], "", &d); err != nil {
107 return nil, err
108 }
109 sort.Slice(d, func(i, j int) bool { return d[i].Path < d[j].Path })
110 return d, nil
111}
112
113// limit is a reading's budget and what it has spent of it.
114type limit struct {
115 budget Budget
116 ctx context.Context // ends at the budget's deadline
117 bytes, entries int64
118}
119
120// spend counts bytes and entries against the budget, and refuses them
121// once either would cross its bound or the deadline has passed. A nil
122// limit spends nothing and refuses nothing.
123func (l *limit) spend(bytes, entries int64) error {
124 if l == nil {
125 return nil
126 }
127 if err := l.late(); err != nil {
128 return err
129 }
130 if l.bytes+bytes > l.budget.Bytes {
131 return fmt.Errorf("%w: the trees take more than the %d bytes it allows", ErrBudget, l.budget.Bytes)
132 }
133 if l.entries+entries > l.budget.Entries {
134 return fmt.Errorf("%w: the trees have more than the %d entries it allows", ErrBudget, l.budget.Entries)
135 }
136 l.bytes += bytes
137 l.entries += entries
138 return nil
139}
140
141// late is the error for a reading whose deadline has passed, or nil.
142func (l *limit) late() error {
143 if l != nil && l.ctx.Err() != nil {
144 return fmt.Errorf("%w: the trees could not be read by its deadline, %s", ErrBudget, l.budget.Deadline.Format(time.RFC3339Nano))
145 }
146 return nil
147}
148
149// failed is the error for a read from git that failed: the deadline's,
150// when it has passed, since passing it is what kills git, and otherwise
151// err.
152func (l *limit) failed(err error) error {
153 if late := l.late(); late != nil {
154 return late
155 }
156 return err
157}
158
159// treeEntry is one entry of a tree object.
160type treeEntry struct {
161 mode, name, oid string
162}
163
164// reader holds one `git cat-file --batch` open, and what it has read.
165type reader struct {
166 repo Repo
167 limit *limit // the budget the reading is held to; nil for none
168 cmd *exec.Cmd
169 in io.WriteCloser
170 out *bufio.Reader
171 hexLen int // an object ID's length in hex, once known
172 trees map[string][]treeEntry // tree → its entries, each tree checked
173 leaves map[string]string // blob → the mode the first entry naming it gave it
174 links map[string]string // blob → the path of the first symlink whose target it is
175 sums map[string][32]byte // blob → the SHA-256 of its content
176}
177
178// maxTarget is the longest symlink target Linux takes: PATH_MAX, 4096
179// bytes, less the NUL that ends it.
180const maxTarget = 4095
181
182// command runs git in the repository. With a limit, git is killed when the
183// limit's deadline passes.
184func (r Repo) command(l *limit, args ...string) *exec.Cmd {
185 program := r.Git
186 if program == "" {
187 program = "git"
188 }
189 args = append([]string{"--no-replace-objects"}, args...)
190 var cmd *exec.Cmd
191 if l == nil {
192 cmd = exec.Command(program, args...)
193 } else {
194 cmd = exec.CommandContext(l.ctx, program, args...)
195 }
196 cmd.Dir = r.Dir
197 cmd.Env = r.Env
198 return cmd
199}
200
201// open starts git cat-file. An unbounded reading asks for each object
202// whole, with --batch. A bounded one asks for its type and size first,
203// with --batch-command, and for its content only once they fit.
204func (r Repo) open(l *limit) (*reader, error) {
205 mode := "--batch"
206 if l != nil {
207 mode = "--batch-command"
208 }
209 cmd := r.command(l, "cat-file", mode)
210 in, err := cmd.StdinPipe()
211 if err != nil {
212 return nil, err
213 }
214 out, err := cmd.StdoutPipe()
215 if err != nil {
216 return nil, err
217 }
218 if err := cmd.Start(); err != nil {
219 return nil, l.failed(fmt.Errorf("could not run git cat-file: %v", err))
220 }
221 return &reader{
222 repo: r, limit: l, cmd: cmd, in: in, out: bufio.NewReader(out),
223 trees: map[string][]treeEntry{}, leaves: map[string]string{}, links: map[string]string{},
224 sums: map[string][32]byte{},
225 }, nil
226}
227
228// close ends the reading. An unbounded one lets git finish. A bounded one
229// kills it, since a reading stopped at a bound may have left an object
230// unread that git would otherwise write out whole.
231func (rd *reader) close() {
232 rd.in.Close()
233 if rd.limit != nil {
234 rd.cmd.Process.Kill()
235 } else {
236 io.Copy(io.Discard, rd.out)
237 }
238 rd.cmd.Wait()
239}
240
241// validID reports whether oid is a full object ID in lowercase hex, of the
242// repository's length once that is known.
243func (rd *reader) validID(oid string) bool {
244 if rd.hexLen != 0 && len(oid) != rd.hexLen {
245 return false
246 }
247 return (len(oid) == 40 || len(oid) == 64) && lowerHex([]byte(oid))
248}
249
250// read reads one object whole, and its type. A bounded reading spends the
251// object's size before asking for its content.
252func (rd *reader) read(oid string) (kind string, data []byte, err error) {
253 if !rd.validID(oid) {
254 return "", nil, fmt.Errorf("%q is not a full object ID", oid)
255 }
256 if rd.limit != nil {
257 kind, size, err := rd.ask("info", oid)
258 if err != nil {
259 return "", nil, err
260 }
261 if err := rd.limit.spend(size, 0); err != nil {
262 return "", nil, err
263 }
264 again, confirmed, err := rd.ask("contents", oid)
265 if err != nil {
266 return "", nil, err
267 }
268 if again != kind || confirmed != size {
269 return "", nil, fmt.Errorf("the object %s changed between being sized and being read", oid)
270 }
271 data, err := rd.content(oid, size)
272 return kind, data, err
273 }
274 kind, size, err := rd.ask("", oid)
275 if err != nil {
276 return "", nil, err
277 }
278 data, err = rd.content(oid, size)
279 return kind, data, err
280}
281
282// ask sends one request for oid, with the command given or none, and reads
283// the header git answers it with: the object's type and size.
284func (rd *reader) ask(command, oid string) (kind string, size int64, err error) {
285 if err := rd.limit.late(); err != nil {
286 return "", 0, err
287 }
288 request := oid + "\n"
289 if command != "" {
290 request = command + " " + request
291 }
292 if _, err := io.WriteString(rd.in, request); err != nil {
293 return "", 0, rd.limit.failed(fmt.Errorf("could not read the object %s: %v", oid, err))
294 }
295 header, err := rd.out.ReadString('\n')
296 if err != nil {
297 return "", 0, rd.limit.failed(fmt.Errorf("could not read the object %s: %v", oid, err))
298 }
299 fields := strings.Fields(header)
300 if len(fields) != 3 || fields[0] != oid {
301 return "", 0, fmt.Errorf("the object %s is not in the repository", oid)
302 }
303 size, err = strconv.ParseInt(fields[2], 10, 64)
304 if err != nil || size < 0 {
305 return "", 0, fmt.Errorf("git gave the size of %s as %q", oid, fields[2])
306 }
307 return fields[1], size, nil
308}
309
310// content reads the size bytes of an object git is writing, and the
311// newline that closes them.
312func (rd *reader) content(oid string, size int64) ([]byte, error) {
313 data := make([]byte, size+1)
314 if _, err := io.ReadFull(rd.out, data); err != nil || data[size] != '\n' {
315 return nil, rd.limit.failed(fmt.Errorf("could not read the object %s whole", oid))
316 }
317 rd.hexLen = len(oid)
318 return data[:size], nil
319}
320
321// treeOf is the tree an object ID names: the tree itself, or a commit's.
322func (rd *reader) treeOf(oid string) (string, error) {
323 kind, data, err := rd.read(oid)
324 if err != nil {
325 return "", err
326 }
327 switch kind {
328 case "tree":
329 return oid, nil
330 case "commit":
331 line, _, _ := strings.Cut(string(data), "\n")
332 tree, ok := strings.CutPrefix(line, "tree ")
333 if !ok || !rd.validID(tree) {
334 return "", fmt.Errorf("the commit %s does not open with its tree", oid)
335 }
336 return tree, nil
337 }
338 return "", fmt.Errorf("%s is a %s, not a tree or a commit", oid, kind)
339}
340
341// check reads a tree and every subtree under it, and refuses one that a
342// checkout could not hold faithfully, as Between describes. Each tree is
343// read and checked once. Its leaves are kept, for checkLeaves. A tree met
344// again is still refused as an empty directory, since it may have been
345// read first as the empty root, which is no directory.
346func (rd *reader) check(oid, at string) error {
347 entries, done := rd.trees[oid]
348 if !done {
349 kind, data, err := rd.read(oid)
350 if err != nil {
351 return err
352 }
353 if kind != "tree" {
354 return fmt.Errorf("%s is a directory whose object %s is a %s", described(at), oid, kind)
355 }
356 if entries, err = rd.parseTree(data, at); err != nil {
357 return err
358 }
359 }
360 if len(entries) == 0 && at != "" {
361 return fmt.Errorf("%s is an empty directory, which a checkout does not hold", described(at))
362 }
363 if done {
364 return nil
365 }
366 rd.trees[oid] = entries
367 for _, e := range entries {
368 path := join(at, e.name)
369 if err := rd.limit.spend(int64(len(path)), 0); err != nil {
370 return err
371 }
372 if e.mode == modeTree {
373 if err := rd.check(e.oid, path); err != nil {
374 return err
375 }
376 continue
377 }
378 if _, seen := rd.leaves[e.oid]; !seen {
379 rd.leaves[e.oid] = e.mode
380 }
381 if _, seen := rd.links[e.oid]; e.mode == ModeSymlink && !seen {
382 rd.links[e.oid] = path
383 }
384 }
385 return nil
386}
387
388// parseTree reads a tree object's entries: "<mode> <name>\0<raw ID>" each.
389func (rd *reader) parseTree(data []byte, at string) ([]treeEntry, error) {
390 size := rd.hexLen / 2
391 var entries []treeEntry
392 names := map[string]bool{}
393 prev := ""
394 for len(data) > 0 {
395 sp := bytes.IndexByte(data, ' ')
396 nul := bytes.IndexByte(data, 0)
397 if sp <= 0 || nul < sp || nul+1+size > len(data) {
398 return nil, fmt.Errorf("the tree at %s is malformed", described(at))
399 }
400 e := treeEntry{mode: string(data[:sp]), name: string(data[sp+1 : nul])}
401 e.oid = hex.EncodeToString(data[nul+1 : nul+1+size])
402 data = data[nul+1+size:]
403 path := join(at, e.name)
404 if err := rd.limit.spend(int64(len(path)), 1); err != nil {
405 return nil, err
406 }
407 if err := checkName(e.name); err != nil {
408 return nil, fmt.Errorf("the tree at %s %w", described(at), err)
409 }
410 switch e.mode {
411 case ModeFile, ModeExec, ModeSymlink, modeTree:
412 case "160000":
413 return nil, fmt.Errorf("%s is a submodule, which valley-delta-v1 does not support", described(path))
414 default:
415 return nil, fmt.Errorf("%s has the mode %q, which valley-delta-v1 does not support", described(path), e.mode)
416 }
417 if names[e.name] {
418 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))
419 }
420 names[e.name] = true
421 // git orders a tree's entries by name, a subtree's read with a
422 // slash after it.
423 key := e.name
424 if e.mode == modeTree {
425 key += "/"
426 }
427 if key <= prev {
428 return nil, fmt.Errorf("the tree at %s holds %q out of git's order", described(at), e.name)
429 }
430 prev = key
431 entries = append(entries, e)
432 }
433 return entries, nil
434}
435
436// checkLeaves refuses an entry whose object is not a blob, or is missing,
437// for every leaf of the trees checked, with one `git cat-file
438// --batch-check`. Then it reads every blob a symlink names, and refuses a
439// target a checkout could not make (checkTarget).
440func (rd *reader) checkLeaves() error {
441 if len(rd.leaves) == 0 {
442 return nil
443 }
444 oids := make([]string, 0, len(rd.leaves))
445 for oid := range rd.leaves {
446 oids = append(oids, oid)
447 }
448 sort.Strings(oids)
449 cmd := rd.repo.command(rd.limit, "cat-file", "--batch-check=%(objectname) %(objecttype)")
450 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
451 out, err := cmd.Output()
452 if err != nil {
453 return rd.limit.failed(fmt.Errorf("could not read the trees' entries: %v", err))
454 }
455 lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n")
456 if len(lines) != len(oids) {
457 return errors.New("could not read the trees' entries")
458 }
459 for i, line := range lines {
460 if line != oids[i]+" blob" {
461 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])
462 }
463 }
464 for _, oid := range oids {
465 path, ok := rd.links[oid]
466 if !ok {
467 continue
468 }
469 _, target, err := rd.read(oid)
470 if err != nil {
471 return err
472 }
473 if err := checkTarget(target); err != nil {
474 return fmt.Errorf("the symlink %s %w", described(path), err)
475 }
476 rd.sums[oid] = sha256.Sum256(target)
477 }
478 return nil
479}
480
481// checkTarget refuses a symlink's target that symlink(2) on Linux would
482// not make: an empty one, one holding a NUL, which would end it early,
483// and one longer than maxTarget.
484func checkTarget(target []byte) error {
485 switch {
486 case len(target) == 0:
487 return fmt.Errorf("has an empty target, which a checkout cannot make")
488 case bytes.IndexByte(target, 0) >= 0:
489 return fmt.Errorf("has a target holding a NUL, which a checkout cannot make")
490 case len(target) > maxTarget:
491 return fmt.Errorf("has a target of %d bytes, longer than Linux's limit of %d", len(target), maxTarget)
492 }
493 return nil
494}
495
496// diff adds to d every path under the directory at whose entries differ
497// between the trees pre and post. Either tree may be "", for none. Equal
498// trees hold equal entries, so they are not read again.
499func (rd *reader) diff(pre, post, at string, d *Delta) error {
500 if pre == post {
501 return nil
502 }
503 byName := map[string][2]*treeEntry{}
504 for side, tree := range []string{pre, post} {
505 if tree == "" {
506 continue
507 }
508 for i := range rd.trees[tree] {
509 e := &rd.trees[tree][i]
510 pair := byName[e.name]
511 pair[side] = e
512 byName[e.name] = pair
513 }
514 }
515 for name, pair := range byName {
516 path := join(at, name)
517 if err := rd.limit.spend(int64(len(path)), 1); err != nil {
518 return err
519 }
520 var sub [2]string
521 var leaf [2]*treeEntry
522 for side, e := range pair {
523 switch {
524 case e == nil:
525 case e.mode == modeTree:
526 sub[side] = e.oid
527 default:
528 leaf[side] = e
529 }
530 }
531 if sub[0] != "" || sub[1] != "" {
532 if err := rd.diff(sub[0], sub[1], path, d); err != nil {
533 return err
534 }
535 }
536 if leaf[0] == nil && leaf[1] == nil {
537 continue
538 }
539 if leaf[0] != nil && leaf[1] != nil && *leaf[0] == *leaf[1] {
540 continue
541 }
542 c := Change{Path: path}
543 var err error
544 if c.Pre, err = rd.image(leaf[0]); err != nil {
545 return err
546 }
547 if c.Post, err = rd.image(leaf[1]); err != nil {
548 return err
549 }
550 if c.Pre != c.Post {
551 *d = append(*d, c)
552 }
553 }
554 return nil
555}
556
557// image is an entry's image: its mode and the SHA-256 of its blob.
558func (rd *reader) image(e *treeEntry) (Image, error) {
559 if e == nil {
560 return Image{}, nil
561 }
562 sum, ok := rd.sums[e.oid]
563 if !ok {
564 kind, data, err := rd.read(e.oid)
565 if err != nil {
566 return Image{}, err
567 }
568 if kind != "blob" {
569 return Image{}, fmt.Errorf("the object %s is a %s, not a blob", e.oid, kind)
570 }
571 sum = sha256.Sum256(data)
572 rd.sums[e.oid] = sum
573 }
574 return Image{Mode: e.mode, Sum: sum}, nil
575}
576
577func join(at, name string) string {
578 if at == "" {
579 return name
580 }
581 return at + "/" + name
582}
583
584// described names a path in an error: the root, or the path quoted.
585func described(path string) string {
586 if path == "" {
587 return "the root"
588 }
589 return strconv.Quote(path)
590}