gunk-dev/the-valley

tree.go

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