| 1 | package 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 | |
| 7 | import ( |
| 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. |
| 22 | type 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. |
| 29 | const 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, or holds a slash; two |
| 39 | // entries with one name, as a file and a directory at one path are; a |
| 40 | // subtree with no entries, which a checkout drops; entries out of git's |
| 41 | // order; and an entry whose object is not the type its mode says. |
| 42 | func Between(r Repo, pre, post string) (Delta, error) { |
| 43 | rd, err := r.open() |
| 44 | if err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | defer rd.close() |
| 48 | var trees [2]string |
| 49 | for i, oid := range []string{pre, post} { |
| 50 | if trees[i], err = rd.treeOf(oid); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | if err := rd.check(trees[i], ""); err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | } |
| 57 | if err := rd.checkLeaves(); err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | var d Delta |
| 61 | if err := rd.diff(trees[0], trees[1], "", &d); err != nil { |
| 62 | return nil, err |
| 63 | } |
| 64 | sort.Slice(d, func(i, j int) bool { return d[i].Path < d[j].Path }) |
| 65 | return d, nil |
| 66 | } |
| 67 | |
| 68 | // treeEntry is one entry of a tree object. |
| 69 | type treeEntry struct { |
| 70 | mode, name, oid string |
| 71 | } |
| 72 | |
| 73 | // reader holds one `git cat-file --batch` open, and what it has read. |
| 74 | type reader struct { |
| 75 | repo Repo |
| 76 | cmd *exec.Cmd |
| 77 | in io.WriteCloser |
| 78 | out *bufio.Reader |
| 79 | hexLen int // an object ID's length in hex, once known |
| 80 | trees map[string][]treeEntry // tree โ its entries, each tree checked |
| 81 | leaves map[string]string // blob โ the mode an entry gave it |
| 82 | sums map[string][32]byte // blob โ the SHA-256 of its content |
| 83 | } |
| 84 | |
| 85 | func (r Repo) command(args ...string) *exec.Cmd { |
| 86 | program := r.Git |
| 87 | if program == "" { |
| 88 | program = "git" |
| 89 | } |
| 90 | cmd := exec.Command(program, append([]string{"--no-replace-objects"}, args...)...) |
| 91 | cmd.Dir = r.Dir |
| 92 | cmd.Env = r.Env |
| 93 | return cmd |
| 94 | } |
| 95 | |
| 96 | func (r Repo) open() (*reader, error) { |
| 97 | cmd := r.command("cat-file", "--batch") |
| 98 | in, err := cmd.StdinPipe() |
| 99 | if err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | out, err := cmd.StdoutPipe() |
| 103 | if err != nil { |
| 104 | return nil, err |
| 105 | } |
| 106 | if err := cmd.Start(); err != nil { |
| 107 | return nil, fmt.Errorf("could not run git cat-file: %v", err) |
| 108 | } |
| 109 | return &reader{ |
| 110 | repo: r, cmd: cmd, in: in, out: bufio.NewReader(out), |
| 111 | trees: map[string][]treeEntry{}, leaves: map[string]string{}, sums: map[string][32]byte{}, |
| 112 | }, nil |
| 113 | } |
| 114 | |
| 115 | func (rd *reader) close() { |
| 116 | rd.in.Close() |
| 117 | io.Copy(io.Discard, rd.out) |
| 118 | rd.cmd.Wait() |
| 119 | } |
| 120 | |
| 121 | // validID reports whether oid is a full object ID in lowercase hex, of the |
| 122 | // repository's length once that is known. |
| 123 | func (rd *reader) validID(oid string) bool { |
| 124 | if rd.hexLen != 0 && len(oid) != rd.hexLen { |
| 125 | return false |
| 126 | } |
| 127 | return (len(oid) == 40 || len(oid) == 64) && lowerHex([]byte(oid)) |
| 128 | } |
| 129 | |
| 130 | // read reads one object whole, and its type. |
| 131 | func (rd *reader) read(oid string) (kind string, data []byte, err error) { |
| 132 | if !rd.validID(oid) { |
| 133 | return "", nil, fmt.Errorf("%q is not a full object ID", oid) |
| 134 | } |
| 135 | if _, err := io.WriteString(rd.in, oid+"\n"); err != nil { |
| 136 | return "", nil, fmt.Errorf("could not read the object %s: %v", oid, err) |
| 137 | } |
| 138 | header, err := rd.out.ReadString('\n') |
| 139 | if err != nil { |
| 140 | return "", nil, fmt.Errorf("could not read the object %s: %v", oid, err) |
| 141 | } |
| 142 | fields := strings.Fields(header) |
| 143 | if len(fields) != 3 || fields[0] != oid { |
| 144 | return "", nil, fmt.Errorf("the object %s is not in the repository", oid) |
| 145 | } |
| 146 | size, err := strconv.ParseInt(fields[2], 10, 64) |
| 147 | if err != nil || size < 0 { |
| 148 | return "", nil, fmt.Errorf("git gave the size of %s as %q", oid, fields[2]) |
| 149 | } |
| 150 | data = make([]byte, size+1) |
| 151 | if _, err := io.ReadFull(rd.out, data); err != nil || data[size] != '\n' { |
| 152 | return "", nil, fmt.Errorf("could not read the object %s whole", oid) |
| 153 | } |
| 154 | rd.hexLen = len(oid) |
| 155 | return fields[1], data[:size], nil |
| 156 | } |
| 157 | |
| 158 | // treeOf is the tree an object ID names: the tree itself, or a commit's. |
| 159 | func (rd *reader) treeOf(oid string) (string, error) { |
| 160 | kind, data, err := rd.read(oid) |
| 161 | if err != nil { |
| 162 | return "", err |
| 163 | } |
| 164 | switch kind { |
| 165 | case "tree": |
| 166 | return oid, nil |
| 167 | case "commit": |
| 168 | line, _, _ := strings.Cut(string(data), "\n") |
| 169 | tree, ok := strings.CutPrefix(line, "tree ") |
| 170 | if !ok || !rd.validID(tree) { |
| 171 | return "", fmt.Errorf("the commit %s does not open with its tree", oid) |
| 172 | } |
| 173 | return tree, nil |
| 174 | } |
| 175 | return "", fmt.Errorf("%s is a %s, not a tree or a commit", oid, kind) |
| 176 | } |
| 177 | |
| 178 | // check reads a tree and every subtree under it, and refuses one that a |
| 179 | // checkout could not hold faithfully, as Between describes. Each tree is |
| 180 | // read and checked once. Its leaves are kept, for checkLeaves. |
| 181 | func (rd *reader) check(oid, at string) error { |
| 182 | if _, done := rd.trees[oid]; done { |
| 183 | return nil |
| 184 | } |
| 185 | kind, data, err := rd.read(oid) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | if kind != "tree" { |
| 190 | return fmt.Errorf("%s is a directory whose object %s is a %s", described(at), oid, kind) |
| 191 | } |
| 192 | entries, err := rd.parseTree(data, at) |
| 193 | if err != nil { |
| 194 | return err |
| 195 | } |
| 196 | if len(entries) == 0 && at != "" { |
| 197 | return fmt.Errorf("%s is an empty directory, which a checkout does not hold", described(at)) |
| 198 | } |
| 199 | rd.trees[oid] = entries |
| 200 | for _, e := range entries { |
| 201 | path := join(at, e.name) |
| 202 | if e.mode == modeTree { |
| 203 | if err := rd.check(e.oid, path); err != nil { |
| 204 | return err |
| 205 | } |
| 206 | continue |
| 207 | } |
| 208 | if _, seen := rd.leaves[e.oid]; !seen { |
| 209 | rd.leaves[e.oid] = e.mode |
| 210 | } |
| 211 | } |
| 212 | return nil |
| 213 | } |
| 214 | |
| 215 | // parseTree reads a tree object's entries: "<mode> <name>\0<raw ID>" each. |
| 216 | func (rd *reader) parseTree(data []byte, at string) ([]treeEntry, error) { |
| 217 | size := rd.hexLen / 2 |
| 218 | var entries []treeEntry |
| 219 | names := map[string]bool{} |
| 220 | prev := "" |
| 221 | for len(data) > 0 { |
| 222 | sp := bytes.IndexByte(data, ' ') |
| 223 | nul := bytes.IndexByte(data, 0) |
| 224 | if sp <= 0 || nul < sp || nul+1+size > len(data) { |
| 225 | return nil, fmt.Errorf("the tree at %s is malformed", described(at)) |
| 226 | } |
| 227 | e := treeEntry{mode: string(data[:sp]), name: string(data[sp+1 : nul])} |
| 228 | e.oid = hex.EncodeToString(data[nul+1 : nul+1+size]) |
| 229 | data = data[nul+1+size:] |
| 230 | path := join(at, e.name) |
| 231 | if err := checkName(e.name); err != nil { |
| 232 | return nil, fmt.Errorf("the tree at %s %w", described(at), err) |
| 233 | } |
| 234 | switch e.mode { |
| 235 | case ModeFile, ModeExec, ModeSymlink, modeTree: |
| 236 | case "160000": |
| 237 | return nil, fmt.Errorf("%s is a submodule, which valley-delta-v1 does not support", described(path)) |
| 238 | default: |
| 239 | return nil, fmt.Errorf("%s has the mode %q, which valley-delta-v1 does not support", described(path), e.mode) |
| 240 | } |
| 241 | if names[e.name] { |
| 242 | 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)) |
| 243 | } |
| 244 | names[e.name] = true |
| 245 | // git orders a tree's entries by name, a subtree's read with a |
| 246 | // slash after it. |
| 247 | key := e.name |
| 248 | if e.mode == modeTree { |
| 249 | key += "/" |
| 250 | } |
| 251 | if key <= prev { |
| 252 | return nil, fmt.Errorf("the tree at %s holds %q out of git's order", described(at), e.name) |
| 253 | } |
| 254 | prev = key |
| 255 | entries = append(entries, e) |
| 256 | } |
| 257 | return entries, nil |
| 258 | } |
| 259 | |
| 260 | // checkLeaves refuses an entry whose object is not a blob, or is missing, |
| 261 | // for every leaf of the trees checked, with one `git cat-file |
| 262 | // --batch-check`. |
| 263 | func (rd *reader) checkLeaves() error { |
| 264 | if len(rd.leaves) == 0 { |
| 265 | return nil |
| 266 | } |
| 267 | oids := make([]string, 0, len(rd.leaves)) |
| 268 | for oid := range rd.leaves { |
| 269 | oids = append(oids, oid) |
| 270 | } |
| 271 | sort.Strings(oids) |
| 272 | cmd := rd.repo.command("cat-file", "--batch-check=%(objectname) %(objecttype)") |
| 273 | cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n") |
| 274 | out, err := cmd.Output() |
| 275 | if err != nil { |
| 276 | return fmt.Errorf("could not read the trees' entries: %v", err) |
| 277 | } |
| 278 | lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") |
| 279 | if len(lines) != len(oids) { |
| 280 | return errors.New("could not read the trees' entries") |
| 281 | } |
| 282 | for i, line := range lines { |
| 283 | if line != oids[i]+" blob" { |
| 284 | 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]) |
| 285 | } |
| 286 | } |
| 287 | return nil |
| 288 | } |
| 289 | |
| 290 | // diff adds to d every path under the directory at whose entries differ |
| 291 | // between the trees pre and post. Either tree may be "", for none. Equal |
| 292 | // trees hold equal entries, so they are not read again. |
| 293 | func (rd *reader) diff(pre, post, at string, d *Delta) error { |
| 294 | if pre == post { |
| 295 | return nil |
| 296 | } |
| 297 | byName := map[string][2]*treeEntry{} |
| 298 | for side, tree := range []string{pre, post} { |
| 299 | if tree == "" { |
| 300 | continue |
| 301 | } |
| 302 | for i := range rd.trees[tree] { |
| 303 | e := &rd.trees[tree][i] |
| 304 | pair := byName[e.name] |
| 305 | pair[side] = e |
| 306 | byName[e.name] = pair |
| 307 | } |
| 308 | } |
| 309 | for name, pair := range byName { |
| 310 | path := join(at, name) |
| 311 | var sub [2]string |
| 312 | var leaf [2]*treeEntry |
| 313 | for side, e := range pair { |
| 314 | switch { |
| 315 | case e == nil: |
| 316 | case e.mode == modeTree: |
| 317 | sub[side] = e.oid |
| 318 | default: |
| 319 | leaf[side] = e |
| 320 | } |
| 321 | } |
| 322 | if sub[0] != "" || sub[1] != "" { |
| 323 | if err := rd.diff(sub[0], sub[1], path, d); err != nil { |
| 324 | return err |
| 325 | } |
| 326 | } |
| 327 | if leaf[0] == nil && leaf[1] == nil { |
| 328 | continue |
| 329 | } |
| 330 | if leaf[0] != nil && leaf[1] != nil && *leaf[0] == *leaf[1] { |
| 331 | continue |
| 332 | } |
| 333 | c := Change{Path: path} |
| 334 | var err error |
| 335 | if c.Pre, err = rd.image(leaf[0]); err != nil { |
| 336 | return err |
| 337 | } |
| 338 | if c.Post, err = rd.image(leaf[1]); err != nil { |
| 339 | return err |
| 340 | } |
| 341 | if c.Pre != c.Post { |
| 342 | *d = append(*d, c) |
| 343 | } |
| 344 | } |
| 345 | return nil |
| 346 | } |
| 347 | |
| 348 | // image is an entry's image: its mode and the SHA-256 of its blob. |
| 349 | func (rd *reader) image(e *treeEntry) (Image, error) { |
| 350 | if e == nil { |
| 351 | return Image{}, nil |
| 352 | } |
| 353 | sum, ok := rd.sums[e.oid] |
| 354 | if !ok { |
| 355 | kind, data, err := rd.read(e.oid) |
| 356 | if err != nil { |
| 357 | return Image{}, err |
| 358 | } |
| 359 | if kind != "blob" { |
| 360 | return Image{}, fmt.Errorf("the object %s is a %s, not a blob", e.oid, kind) |
| 361 | } |
| 362 | sum = sha256.Sum256(data) |
| 363 | rd.sums[e.oid] = sum |
| 364 | } |
| 365 | return Image{Mode: e.mode, Sum: sum}, nil |
| 366 | } |
| 367 | |
| 368 | func join(at, name string) string { |
| 369 | if at == "" { |
| 370 | return name |
| 371 | } |
| 372 | return at + "/" + name |
| 373 | } |
| 374 | |
| 375 | // described names a path in an error: the root, or the path quoted. |
| 376 | func described(path string) string { |
| 377 | if path == "" { |
| 378 | return "the root" |
| 379 | } |
| 380 | return strconv.Quote(path) |
| 381 | } |