gunk-dev/the-valley

git.go

source4f919451c78bmain's published tip history
9.1 KiB
1package review
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "os/exec"
12 "strconv"
13 "strings"
14 "time"
15
16 "the-valley/change"
17 "the-valley/delta"
18)
19
20// Repo is a git repository reviews are read from and written to, and how
21// git is run in it: the program, the directory, and the environment. It
22// is the repository valley-delta-v1 reads, so one value names both.
23type Repo = delta.Repo
24
25// hashSize is the bytes of an object ID. A review names commits as a
26// change record does, by SHA-1, so it is read from a SHA-1 repository.
27const hashSize = 20
28
29// command runs git in the repository with replacement refs off, killed
30// when ctx ends.
31func command(ctx context.Context, r Repo, args ...string) *exec.Cmd {
32 program := r.Git
33 if program == "" {
34 program = "git"
35 }
36 cmd := exec.CommandContext(ctx, program, append([]string{"--no-replace-objects"}, args...)...)
37 cmd.Dir = r.Dir
38 cmd.Env = r.Env
39 return cmd
40}
41
42// git runs git in the repository and returns its standard output. A git
43// killed at the deadline is reported as late.
44func git(ctx context.Context, r Repo, stdin []byte, args ...string) ([]byte, error) {
45 cmd := command(ctx, r, args...)
46 if stdin != nil {
47 cmd.Stdin = bytes.NewReader(stdin)
48 }
49 var stderr bytes.Buffer
50 cmd.Stderr = &stderr
51 out, err := cmd.Output()
52 if err != nil {
53 if ctx.Err() != nil {
54 return nil, late(ctx)
55 }
56 if msg := strings.TrimSpace(stderr.String()); msg != "" {
57 return out, fmt.Errorf("git %s: %w: %s", args[0], err, msg)
58 }
59 return out, fmt.Errorf("git %s: %w", args[0], err)
60 }
61 return out, nil
62}
63
64// late is the error for a reading whose deadline has passed. It wraps
65// delta.ErrBudget, the way a delta's reading past its deadline does.
66func late(ctx context.Context) error {
67 until, _ := ctx.Deadline()
68 return fmt.Errorf("%w: the review could not be read by its deadline, %s", delta.ErrBudget, until.Format(time.RFC3339Nano))
69}
70
71// objects reads objects one at a time out of one
72// `git cat-file --batch-command`. It asks for an object's type and size
73// first, and for its content only once they pass every bound, so git never
74// produces an object a reading would refuse.
75type objects struct {
76 ctx context.Context
77 cmd *exec.Cmd
78 in io.WriteCloser
79 out *bufio.Reader
80 bytes int64 // the bytes the stream may read in all
81 spent int64
82}
83
84// openObjects starts git cat-file, to read at most bytes in all before
85// ctx ends.
86func openObjects(ctx context.Context, r Repo, bytes int64) (*objects, error) {
87 cmd := command(ctx, r, "cat-file", "--batch-command")
88 in, err := cmd.StdinPipe()
89 if err != nil {
90 return nil, err
91 }
92 out, err := cmd.StdoutPipe()
93 if err != nil {
94 return nil, err
95 }
96 if err := cmd.Start(); err != nil {
97 if ctx.Err() != nil {
98 return nil, late(ctx)
99 }
100 return nil, fmt.Errorf("could not run git cat-file: %v", err)
101 }
102 return &objects{ctx: ctx, cmd: cmd, in: in, out: bufio.NewReader(out), bytes: bytes}, nil
103}
104
105// close kills git rather than asking it to finish, since a reading that
106// stopped at a bound has nothing more to ask.
107func (o *objects) close() {
108 o.in.Close()
109 o.cmd.Process.Kill()
110 o.cmd.Wait()
111}
112
113// failed is the error for a read or write of the stream that failed: the
114// deadline's, when it has passed, since that is what kills git.
115func (o *objects) failed(err error) error {
116 if o.ctx.Err() != nil {
117 return late(o.ctx)
118 }
119 return err
120}
121
122// errMissing is ask's error for a name git finds no object for.
123var errMissing = errors.New("is no object in the repository")
124
125// ask sends one command and reads git's answer: the object's ID, type and
126// size, or that it is missing.
127func (o *objects) ask(command, name string) (id, kind string, size int64, err error) {
128 if o.ctx.Err() != nil {
129 return "", "", 0, late(o.ctx)
130 }
131 if _, err := fmt.Fprintf(o.in, "%s %s\n", command, name); err != nil {
132 return "", "", 0, o.failed(fmt.Errorf("could not be asked for: %v", err))
133 }
134 header, err := o.out.ReadString('\n')
135 if err != nil {
136 return "", "", 0, o.failed(fmt.Errorf("could not be read: %v", err))
137 }
138 // git answers a name it finds nothing for with the name as asked, which
139 // may hold spaces, and then "missing".
140 if strings.TrimSuffix(header, "\n") == name+" missing" {
141 return "", "", 0, errMissing
142 }
143 fields := strings.Fields(header)
144 if len(fields) != 3 {
145 return "", "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header))
146 }
147 size, err = strconv.ParseInt(fields[2], 10, 64)
148 if err != nil || size < 0 {
149 return "", "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header))
150 }
151 return fields[0], fields[1], size, nil
152}
153
154// info is the ID, type and size of the object name names, which may be an
155// object ID or <commit>:<path>.
156func (o *objects) info(name string) (id, kind string, size int64, err error) {
157 return o.ask("info", name)
158}
159
160// read returns the content of the object id, which must be of type kind
161// and at most max bytes, and must fit what is left of the stream's bytes.
162func (o *objects) read(id, kind string, max int64) ([]byte, error) {
163 _, got, size, err := o.ask("info", id)
164 switch {
165 case err != nil:
166 return nil, err
167 case got != kind:
168 return nil, fmt.Errorf("is a %s, where a %s is expected", got, kind)
169 case size > max:
170 return nil, fmt.Errorf("is a %s of %d bytes, more than the %d it may be", kind, size, max)
171 case o.spent+size > o.bytes:
172 return nil, fmt.Errorf("%w: reading it would take more than the %d bytes the reading may", delta.ErrBudget, o.bytes)
173 }
174 _, again, confirmed, err := o.ask("contents", id)
175 if err != nil {
176 return nil, err
177 }
178 if again != kind || confirmed != size {
179 return nil, fmt.Errorf("changed between being sized and being read: git answered %s %d", again, confirmed)
180 }
181 o.spent += size
182 body := make([]byte, size+1) // the content and git's closing newline
183 if _, err := io.ReadFull(o.out, body); err != nil || body[size] != '\n' {
184 return nil, o.failed(errors.New("could not be read whole"))
185 }
186 return body[:size], nil
187}
188
189// oneFile is the layout of a commit whose tree holds one plain file and
190// nothing else, and the bounds on its objects: a review commit's, and a
191// change record commit's.
192type oneFile struct {
193 subject string // what such a commit is, as a refusal names it
194 name string // the one file its tree holds
195 commit, tree, blob int64 // the most bytes each of its objects may hold
196}
197
198// readOneFile reads the commit id as a commit of the layout given: its
199// parents, in order, and its one file. Each object is held to its bound
200// before its content is read.
201func (o *objects) readOneFile(id string, l oneFile) (parents []string, file []byte, err error) {
202 if !validObjectID(id) {
203 return nil, nil, fmt.Errorf("%q is not a full SHA-1 object ID", id)
204 }
205 body, err := o.read(id, "commit", l.commit)
206 if err != nil {
207 return nil, nil, fmt.Errorf("%s %s %w", l.subject, id, err)
208 }
209 tree, parents, err := commitLinks(body)
210 if err != nil {
211 return nil, nil, fmt.Errorf("%s %s %w", l.subject, id, err)
212 }
213 entries, err := o.read(tree, "tree", l.tree)
214 if err != nil {
215 return nil, nil, fmt.Errorf("the tree of %s %s %w", l.subject, id, err)
216 }
217 want := "100644 " + l.name + "\x00"
218 if len(entries) != len(want)+hashSize || string(entries[:len(want)]) != want {
219 return nil, nil, fmt.Errorf("the tree of %s %s holds something other than %s alone, as a plain file", l.subject, id, l.name)
220 }
221 blob := hex.EncodeToString(entries[len(want):])
222 if file, err = o.read(blob, "blob", l.blob); err != nil {
223 return nil, nil, fmt.Errorf("the %s of %s %s %w", l.name, l.subject, id, err)
224 }
225 return parents, file, nil
226}
227
228// commitLinks reads the tree and the parents out of a commit object, as
229// git reads them: a tree line first, and then every parent line that
230// follows it directly. A parent line anywhere later is one git ignores,
231// and a commit that holds one is refused rather than read two ways.
232func commitLinks(body []byte) (tree string, parents []string, err error) {
233 header, _, _ := bytes.Cut(body, []byte("\n\n"))
234 lines := strings.Split(string(header), "\n")
235 tree, ok := strings.CutPrefix(lines[0], "tree ")
236 if !ok || !validObjectID(tree) {
237 return "", nil, errors.New("is a commit git could not have written: it does not open with its tree")
238 }
239 rest := lines[1:]
240 for len(rest) > 0 && strings.HasPrefix(rest[0], "parent ") {
241 parent := strings.TrimPrefix(rest[0], "parent ")
242 if !validObjectID(parent) {
243 return "", nil, errors.New("is a commit git could not have written: a parent is not an object ID")
244 }
245 parents = append(parents, parent)
246 rest = rest[1:]
247 }
248 for _, line := range rest {
249 if strings.HasPrefix(line, "parent ") {
250 return "", nil, errors.New("names a parent after its other headers, which git does not read as a parent")
251 }
252 }
253 return tree, parents, nil
254}
255
256// validObjectID reports whether s is a full SHA-1 object ID in lowercase
257// hex.
258func validObjectID(s string) bool {
259 return len(s) == 2*hashSize && lowerHex(s)
260}
261
262// none reports whether id names no commit: empty, or git's all-zero ID.
263func none(id string) bool {
264 return strings.Trim(id, "0") == ""
265}
266
267// objectOf is the object ID a git-sha1:<hex> name stands for.
268func objectOf(name string) string {
269 return strings.TrimPrefix(name, change.HeadPrefix)
270}