| 1 | package review |
| 2 | |
| 3 | import ( |
| 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. |
| 23 | type 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. |
| 27 | const hashSize = 20 |
| 28 | |
| 29 | // command runs git in the repository with replacement refs off, killed |
| 30 | // when ctx ends. |
| 31 | func 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. |
| 44 | func 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. |
| 66 | func 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. |
| 75 | type 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. |
| 86 | func 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. |
| 107 | func (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. |
| 115 | func (o *objects) failed(err error) error { |
| 116 | if o.ctx.Err() != nil { |
| 117 | return late(o.ctx) |
| 118 | } |
| 119 | return err |
| 120 | } |
| 121 | |
| 122 | // ask sends one command and reads git's answer: the object's ID, type and |
| 123 | // size, or that it is missing. |
| 124 | func (o *objects) ask(command, name string) (id, kind string, size int64, err error) { |
| 125 | if o.ctx.Err() != nil { |
| 126 | return "", "", 0, late(o.ctx) |
| 127 | } |
| 128 | if _, err := fmt.Fprintf(o.in, "%s %s\n", command, name); err != nil { |
| 129 | return "", "", 0, o.failed(fmt.Errorf("could not be asked for: %v", err)) |
| 130 | } |
| 131 | header, err := o.out.ReadString('\n') |
| 132 | if err != nil { |
| 133 | return "", "", 0, o.failed(fmt.Errorf("could not be read: %v", err)) |
| 134 | } |
| 135 | fields := strings.Fields(header) |
| 136 | if len(fields) == 2 && fields[1] == "missing" { |
| 137 | return "", "", 0, errors.New("is no object in the repository") |
| 138 | } |
| 139 | if len(fields) != 3 { |
| 140 | return "", "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header)) |
| 141 | } |
| 142 | size, err = strconv.ParseInt(fields[2], 10, 64) |
| 143 | if err != nil || size < 0 { |
| 144 | return "", "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header)) |
| 145 | } |
| 146 | return fields[0], fields[1], size, nil |
| 147 | } |
| 148 | |
| 149 | // info is the ID, type and size of the object name names, which may be an |
| 150 | // object ID or <commit>:<path>. |
| 151 | func (o *objects) info(name string) (id, kind string, size int64, err error) { |
| 152 | return o.ask("info", name) |
| 153 | } |
| 154 | |
| 155 | // read returns the content of the object id, which must be of type kind |
| 156 | // and at most max bytes, and must fit what is left of the stream's bytes. |
| 157 | func (o *objects) read(id, kind string, max int64) ([]byte, error) { |
| 158 | _, got, size, err := o.ask("info", id) |
| 159 | switch { |
| 160 | case err != nil: |
| 161 | return nil, err |
| 162 | case got != kind: |
| 163 | return nil, fmt.Errorf("is a %s, where a %s is expected", got, kind) |
| 164 | case size > max: |
| 165 | return nil, fmt.Errorf("is a %s of %d bytes, more than the %d it may be", kind, size, max) |
| 166 | case o.spent+size > o.bytes: |
| 167 | return nil, fmt.Errorf("%w: reading it would take more than the %d bytes the reading may", delta.ErrBudget, o.bytes) |
| 168 | } |
| 169 | _, again, confirmed, err := o.ask("contents", id) |
| 170 | if err != nil { |
| 171 | return nil, err |
| 172 | } |
| 173 | if again != kind || confirmed != size { |
| 174 | return nil, fmt.Errorf("changed between being sized and being read: git answered %s %d", again, confirmed) |
| 175 | } |
| 176 | o.spent += size |
| 177 | body := make([]byte, size+1) // the content and git's closing newline |
| 178 | if _, err := io.ReadFull(o.out, body); err != nil || body[size] != '\n' { |
| 179 | return nil, o.failed(errors.New("could not be read whole")) |
| 180 | } |
| 181 | return body[:size], nil |
| 182 | } |
| 183 | |
| 184 | // oneFile is the layout of a commit whose tree holds one plain file and |
| 185 | // nothing else, and the bounds on its objects: a review commit's, and a |
| 186 | // change record commit's. |
| 187 | type oneFile struct { |
| 188 | subject string // what such a commit is, as a refusal names it |
| 189 | name string // the one file its tree holds |
| 190 | commit, tree, blob int64 // the most bytes each of its objects may hold |
| 191 | } |
| 192 | |
| 193 | // readOneFile reads the commit id as a commit of the layout given: its |
| 194 | // parents, in order, and its one file. Each object is held to its bound |
| 195 | // before its content is read. |
| 196 | func (o *objects) readOneFile(id string, l oneFile) (parents []string, file []byte, err error) { |
| 197 | if !validObjectID(id) { |
| 198 | return nil, nil, fmt.Errorf("%q is not a full SHA-1 object ID", id) |
| 199 | } |
| 200 | body, err := o.read(id, "commit", l.commit) |
| 201 | if err != nil { |
| 202 | return nil, nil, fmt.Errorf("%s %s %w", l.subject, id, err) |
| 203 | } |
| 204 | tree, parents, err := commitLinks(body) |
| 205 | if err != nil { |
| 206 | return nil, nil, fmt.Errorf("%s %s %w", l.subject, id, err) |
| 207 | } |
| 208 | entries, err := o.read(tree, "tree", l.tree) |
| 209 | if err != nil { |
| 210 | return nil, nil, fmt.Errorf("the tree of %s %s %w", l.subject, id, err) |
| 211 | } |
| 212 | want := "100644 " + l.name + "\x00" |
| 213 | if len(entries) != len(want)+hashSize || string(entries[:len(want)]) != want { |
| 214 | 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) |
| 215 | } |
| 216 | blob := hex.EncodeToString(entries[len(want):]) |
| 217 | if file, err = o.read(blob, "blob", l.blob); err != nil { |
| 218 | return nil, nil, fmt.Errorf("the %s of %s %s %w", l.name, l.subject, id, err) |
| 219 | } |
| 220 | return parents, file, nil |
| 221 | } |
| 222 | |
| 223 | // commitLinks reads the tree and the parents out of a commit object, as |
| 224 | // git reads them: a tree line first, and then every parent line that |
| 225 | // follows it directly. A parent line anywhere later is one git ignores, |
| 226 | // and a commit that holds one is refused rather than read two ways. |
| 227 | func commitLinks(body []byte) (tree string, parents []string, err error) { |
| 228 | header, _, _ := bytes.Cut(body, []byte("\n\n")) |
| 229 | lines := strings.Split(string(header), "\n") |
| 230 | tree, ok := strings.CutPrefix(lines[0], "tree ") |
| 231 | if !ok || !validObjectID(tree) { |
| 232 | return "", nil, errors.New("is a commit git could not have written: it does not open with its tree") |
| 233 | } |
| 234 | rest := lines[1:] |
| 235 | for len(rest) > 0 && strings.HasPrefix(rest[0], "parent ") { |
| 236 | parent := strings.TrimPrefix(rest[0], "parent ") |
| 237 | if !validObjectID(parent) { |
| 238 | return "", nil, errors.New("is a commit git could not have written: a parent is not an object ID") |
| 239 | } |
| 240 | parents = append(parents, parent) |
| 241 | rest = rest[1:] |
| 242 | } |
| 243 | for _, line := range rest { |
| 244 | if strings.HasPrefix(line, "parent ") { |
| 245 | return "", nil, errors.New("names a parent after its other headers, which git does not read as a parent") |
| 246 | } |
| 247 | } |
| 248 | return tree, parents, nil |
| 249 | } |
| 250 | |
| 251 | // validObjectID reports whether s is a full SHA-1 object ID in lowercase |
| 252 | // hex. |
| 253 | func validObjectID(s string) bool { |
| 254 | return len(s) == 2*hashSize && lowerHex(s) |
| 255 | } |
| 256 | |
| 257 | // none reports whether id names no commit: empty, or git's all-zero ID. |
| 258 | func none(id string) bool { |
| 259 | return strings.Trim(id, "0") == "" |
| 260 | } |
| 261 | |
| 262 | // objectOf is the object ID a git-sha1:<hex> name stands for. |
| 263 | func objectOf(name string) string { |
| 264 | return strings.TrimPrefix(name, change.HeadPrefix) |
| 265 | } |