Public: anyone can read this; the crew can change it.

A commit is written by one git fast-import and landed by one update-ref: two git processes instead of six #17526

opened this

Merged 17h 15m ago, live in production

commit-fast-import → main 0 commits

  • Merged. commit-fast-import was merged into main as aefaf51.

Review

Sign in to review this change.
3 files changed +361 −2
scripts/unused-exports-allow.json +2
@@ -1,4 +1,6 @@
11 [
2 "src/git/write.ts setCommitClock",
3 "src/git/write.ts setCommitRoute",
24 "src/checks/wide.ts setWideIdleSource",
35 "src/maintain/edge_copy.ts forgetPushed",
46 "src/apps/check-memory.ts usePodMemoryFile",
src/git/write.ts +164 −2
@@ -1,9 +1,19 @@
11 /**
22 * Committing files to a branch through pure plumbing — no work tree, no push.
3 * A temporary index (GIT_INDEX_FILE) is populated with hash-object'd blobs,
4 * written to a tree, sealed with commit-tree, and landed with a CAS update-ref.
53 * This is how automation (and the API) writes code without a git client — the
64 * primitive an AI harness leans on.
5 *
6 * Two ways to the same commit, landed the same way (a CAS update-ref):
7 *
8 * - one `git fast-import` (#16876): the blobs, the tree from the parent's with
9 * the commit's changes, and the commit itself, written by one process that
10 * leaves no ref behind (the commit's scratch branch is reset to nothing
11 * before it ends) and answers the commit's id. Two git processes a commit
12 * instead of six; the commit's bytes are the same.
13 * - a temporary index (GIT_INDEX_FILE) populated with hash-object'd blobs,
14 * written to a tree and sealed with commit-tree: for what the first does
15 * not take on (a signed commit, a merge built on a seed tree, an identity
16 * git would clean up first), and whenever the first cannot be sure.
717 */
818
919 import { mkdir, rm, writeFile } from "node:fs/promises";
@@ -13,6 +23,7 @@ import { err, ok, type Result } from "../kernel/result.ts";
1323 import { runGit } from "./env.ts";
1424 import { isSafeRef, isSafeTreePath } from "./guard.ts";
1525 import { resolveOid } from "./merge.ts";
26 import { readerFor } from "./read.ts";
1627
1728 /** Most files of one commit being written to its staging directory at once. */
1829 const WRITE_POOL = 16;
@@ -39,6 +50,59 @@ export type CommitFilesError =
3950 const hasGitComponent = (path: string): boolean =>
4051 path.split("/").some((part) => part.toLowerCase() === ".git");
4152
53 /** The time a commit is stamped with: seconds since the epoch and the zone, as git writes them. */
54 export interface CommitClock {
55 readonly seconds: number;
56 /** `+HHMM` / `-HHMM`. */
57 readonly zone: string;
58 }
59
60 const zoneOf = (offsetMinutes: number): string => {
61 const sign = offsetMinutes < 0 ? "-" : "+";
62 const abs = Math.abs(offsetMinutes);
63 return `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}${String(abs % 60).padStart(2, "0")}`;
64 };
65
66 const systemClock = (): CommitClock => {
67 const now = new Date();
68 return { seconds: Math.floor(now.getTime() / 1000), zone: zoneOf(-now.getTimezoneOffset()) };
69 };
70 let clock: () => CommitClock = systemClock;
71
72 /** Tests fix the time a commit is stamped with; pass nothing to restore the system's. */
73 export function setCommitClock(fixed?: () => CommitClock): void {
74 clock = fixed ?? systemClock;
75 }
76
77 /** Which way the next commits are written; tests compare the two. @default "fast-import" */
78 let route: "fast-import" | "index" = "fast-import";
79
80 /** Tests write a commit the index's way, to compare it with fast-import's. */
81 export function setCommitRoute(next: "fast-import" | "index" = "fast-import"): void {
82 route = next;
83 }
84
85 /**
86 * An identity git writes as given. `commit-tree` trims what git calls crud (`.,:;<>"\'` and
87 * whitespace) from each end of a name and email and drops `<` and `>`; fast-import refuses them.
88 * Anything it would change goes the index's way, so both ways write the same bytes.
89 */
90 const CRUD = /^[\s.,:;<>"\\']|[\s.,:;<>"\\']$/;
91 const plainIdentity = (who: { name: string; email: string }): boolean =>
92 [who.name, who.email].every((part) => part !== "" && !/[<>\n\0]/.test(part) && !CRUD.test(part));
93
94 /** A path as fast-import reads it: in double quotes, C-escaped, so no byte of it is ever syntax. */
95 function quotePath(path: string): string {
96 let out = '"';
97 for (const ch of path) {
98 const code = ch.codePointAt(0)!;
99 if (ch === '"' || ch === "\\") out += `\\${ch}`;
100 else if (code < 0x20 || code === 0x7f) out += `\\${code.toString(8).padStart(3, "0")}`;
101 else out += ch;
102 }
103 return `${out}"`;
104 }
105
42106 export interface CommitResult {
43107 readonly commitOid: string;
44108 readonly branch: string;
@@ -120,6 +184,17 @@ export async function commitFiles(
120184 if (input.expectTip !== undefined && tip !== input.expectTip)
121185 return err({ kind: "branch_moved" });
122186
187 if (
188 route === "fast-import" &&
189 input.sign === undefined &&
190 input.seedTree === undefined &&
191 input.mergeParents === undefined &&
192 plainIdentity(input.author)
193 ) {
194 const written = await fastCommit(dir, input, tip, parent);
195 if (written !== undefined) return written;
196 }
197
123198 // Seed the index from the parent's tree, or empty for a first commit.
124199 const seed = parent || input.seedTree
125200 ? await runGit(["read-tree", input.seedTree ?? `${parent}^{tree}`], { cwd: dir, env })
@@ -208,11 +283,14 @@ export async function commitFiles(
208283 const tree = await runGit(["write-tree"], { cwd: dir, env });
209284 if (!tree.ok) return err({ kind: "git", message: tree.error.stderr });
210285
286 const at = clock();
211287 const commitEnv = {
212288 GIT_AUTHOR_NAME: input.author.name,
213289 GIT_AUTHOR_EMAIL: input.author.email,
214290 GIT_COMMITTER_NAME: input.author.name,
215291 GIT_COMMITTER_EMAIL: input.author.email,
292 GIT_AUTHOR_DATE: `@${at.seconds} ${at.zone}`,
293 GIT_COMMITTER_DATE: `@${at.seconds} ${at.zone}`,
216294 };
217295 const parents = [
218296 ...(parent ? ["-p", parent] : []),
@@ -257,3 +335,87 @@ export async function commitFiles(
257335 await rm(blobsDir, { recursive: true, force: true });
258336 }
259337 }
338
339 /** What a path is in `rev`'s tree, read through the repository's long-lived `cat-file` reader. */
340 async function kindAt(dir: string, rev: string, path: string): Promise<"blob" | "tree" | "none"> {
341 const stat = await readerFor(dir).stat(`${rev}:${path}`);
342 if (!stat.ok) return "none";
343 return stat.value.type === "tree" ? "tree" : stat.value.type === "blob" ? "blob" : "none";
344 }
345
346 /**
347 * One commit by `git fast-import`, landed as the index's way lands one. Undefined when it cannot
348 * be sure (the reader failed, or fast-import did): the caller then writes it the index's way.
349 *
350 * What `update-index` refuses is refused first, with the same answer: a file where the parent (or
351 * an earlier file of this commit) has a directory, or under a path that is a file. A deletion of
352 * a path that is not a file in the tree is a no-op there, and so is left out here.
353 */
354 async function fastCommit(
355 dir: string,
356 input: Parameters<typeof commitFiles>[1],
357 tip: string | undefined,
358 parent: string | undefined,
359 ): Promise<Result<CommitResult, CommitFilesError> | undefined> {
360 const files = new Map<string, boolean>(); // path -> a file (true) or deleted (false), so far
361 const dirs = new Set<string>(); // directories this commit's files make
362 const ops: (string | Uint8Array)[] = [];
363 const encoder = new TextEncoder();
364 try {
365 for (const file of input.files) {
366 const parts = file.path.split("/");
367 if (file.content === null) {
368 const now = files.get(file.path);
369 const was = now === undefined && parent !== undefined ? await kindAt(dir, parent, file.path) : "none";
370 if (now === true || was === "blob") ops.push(`D ${quotePath(file.path)}\n`);
371 files.set(file.path, false);
372 continue;
373 }
374 // A directory where this file goes, from the parent or from this commit.
375 if (dirs.has(file.path)) return err({ kind: "path_conflict", path: file.path });
376 if (files.get(file.path) === undefined && parent !== undefined && (await kindAt(dir, parent, file.path)) === "tree")
377 return err({ kind: "path_conflict", path: file.path });
378 // A file where one of its directories goes, from this commit or from the parent.
379 for (let n = 1; n < parts.length; n++) {
380 const above = parts.slice(0, n).join("/");
381 const mine = files.get(above);
382 if (mine === true) return err({ kind: "path_conflict", path: file.path });
383 if (mine === undefined && parent !== undefined && (await kindAt(dir, parent, above)) === "blob")
384 return err({ kind: "path_conflict", path: file.path });
385 }
386 for (let n = 1; n < parts.length; n++) dirs.add(parts.slice(0, n).join("/"));
387 files.set(file.path, true);
388 const bytes = typeof file.content === "string" ? encoder.encode(file.content) : file.content;
389 ops.push(`M ${file.mode ?? "100644"} inline ${quotePath(file.path)}\ndata ${bytes.length}\n`, bytes, "\n");
390 }
391 } catch {
392 return undefined;
393 }
394
395 const at = clock();
396 const who = `${input.author.name} <${input.author.email}> ${at.seconds} ${at.zone}`;
397 // `commit-tree -m` ends the message with a newline when it has none.
398 const message = encoder.encode(input.message.endsWith("\n") || input.message === "" ? input.message : `${input.message}\n`);
399 // A branch of this process's own, reset to nothing before fast-import ends: it leaves no ref.
400 const scratch = `refs/forge-commit/${id()}`;
401 const head = `commit ${scratch}\nmark :1\nauthor ${who}\ncommitter ${who}\ndata ${message.length}\n`;
402 const stream = [head, message, "\n", ...(parent === undefined ? [] : [`from ${parent}\n`]), ...ops, "\n", `reset ${scratch}\nfrom ${"0".repeat(40)}\n\n`, "get-mark :1\n"];
403 const parts = stream.map((part) => (typeof part === "string" ? encoder.encode(part) : part));
404 const body = new Uint8Array(parts.reduce((n, part) => n + part.length, 0));
405 let offset = 0;
406 for (const part of parts) {
407 body.set(part, offset);
408 offset += part.length;
409 }
410 const imported = await runGit(["fast-import", "--quiet", "--date-format=raw"], { cwd: dir, stdin: body });
411 const commitOid = imported.ok ? imported.value.trim() : "";
412 if (!/^[0-9a-f]{40,64}$/.test(commitOid)) return undefined;
413
414 if (input.land) {
415 const landed = await input.land(commitOid, tip);
416 if (!landed.ok) return err({ kind: "land_refused", message: landed.error });
417 }
418 const update = await runGit(["update-ref", `refs/heads/${input.branch}`, commitOid, tip ?? "0".repeat(40)], { cwd: dir });
419 if (!update.ok) return err({ kind: "branch_moved" });
420 return ok({ commitOid, branch: input.branch, created: tip === undefined });
421 }
test/commit-fast-import.test.ts added +195
@@ -0,0 +1,195 @@
1 /**
2 * A commit by `git fast-import` (`src/git/write.ts`, #16876) is the same commit the index's way
3 * writes: the same id for the same input when the time is fixed, landed by the same
4 * compare-and-swap, in two git processes instead of six. What it does not take on (a signed
5 * commit, a merge on a seed tree, an identity git would clean up) goes the index's way.
6 */
7 import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { runGit } from "../src/git/env.ts";
12 import { initBareRepo } from "../src/git/repos.ts";
13 import { commitFiles, setCommitClock, setCommitRoute, type FileWrite } from "../src/git/write.ts";
14 import { unwrap } from "../src/kernel/result.ts";
15 import { gitSpawns } from "./helpers/work.ts";
16
17 let root = "";
18 let n = 0;
19 beforeAll(async () => {
20 root = await mkdtemp(join(tmpdir(), "forge-fast-import-"));
21 setCommitClock(() => ({ seconds: 1_764_000_000, zone: "+0000" }));
22 });
23 afterEach(() => setCommitRoute());
24 afterAll(async () => {
25 setCommitClock();
26 setCommitRoute();
27 await rm(root, { recursive: true, force: true });
28 });
29
30 const repo = async (): Promise<string> => {
31 const dir = join(root, `r${n++}.git`);
32 unwrap(await initBareRepo(dir));
33 return dir;
34 };
35 const author = { name: "Mel Tester", email: "[email protected]" };
36
37 type Step = { branch: string; message: string; files: FileWrite[]; startPoint?: string };
38 const STEPS: Step[] = [
39 {
40 branch: "main",
41 message: "first",
42 files: [
43 { path: "README.md", content: "hello\n" },
44 { path: "src/a.ts", content: "export const a = 1;\n" },
45 ],
46 },
47 {
48 branch: "main",
49 message: "second\n\nwith a body\n",
50 files: [
51 { path: "src/deep/b.ts", content: "b" },
52 { path: "bin/run", content: "#!/bin/sh\necho hi\n", mode: "100755" },
53 { path: "data/raw.bin", content: new Uint8Array([0, 1, 2, 255, 10, 13]) },
54 { path: 'odd "name" é\\here.txt', content: "odd" },
55 ],
56 },
57 {
58 branch: "main",
59 message: "third: a deletion, a re-write and a no-op deletion",
60 files: [
61 { path: "src/a.ts", content: null },
62 { path: "README.md", content: "hello again\n" },
63 { path: "never/was.txt", content: null },
64 { path: "src", content: null },
65 ],
66 },
67 { branch: "feature", startPoint: "main", message: "a branch from main", files: [{ path: "feature.txt", content: "f" }] },
68 {
69 branch: "main",
70 message: "a deleted file's place taken by a directory",
71 files: [
72 { path: "README.md", content: null },
73 { path: "README.md/inside.txt", content: "now a directory" },
74 ],
75 },
76 ];
77
78 async function play(dir: string): Promise<string[]> {
79 const ids: string[] = [];
80 for (const step of STEPS) {
81 const done = unwrap(await commitFiles(dir, { ...step, author }));
82 ids.push(done.commitOid);
83 }
84 return ids;
85 }
86
87 describe("the same commit either way", () => {
88 test("for the same input and time, fast-import's commits have the index's ids, one by one", async () => {
89 setCommitRoute("index");
90 const byIndex = await play(await repo());
91 setCommitRoute("fast-import");
92 const fast = await repo();
93 const byImport = await play(fast);
94 expect(byImport).toEqual(byIndex);
95 // And it leaves no ref of its own behind, only the branches.
96 const refs = unwrap(await runGit(["for-each-ref", "--format=%(refname)"], { cwd: fast }));
97 expect(refs.split("\n").sort()).toEqual(["refs/heads/feature", "refs/heads/main"]);
98 });
99
100 test("a signed commit, and an identity git would trim, go the index's way and are still the same", async () => {
101 const sign = (commit: string): string => `-----BEGIN SIG-----\n${commit.length}\n-----END SIG-----`;
102 const odd = { name: " Mel. ", email: "[email protected]" };
103 const ids: string[][] = [];
104 for (const way of ["index", "fast-import"] as const) {
105 setCommitRoute(way);
106 const dir = await repo();
107 const signed = unwrap(
108 await commitFiles(dir, { branch: "main", message: "signed", files: [{ path: "a", content: "a" }], author, sign }),
109 );
110 const trimmed = unwrap(
111 await commitFiles(dir, { branch: "main", message: "trimmed", files: [{ path: "b", content: "b" }], author: odd }),
112 );
113 ids.push([signed.commitOid, trimmed.commitOid]);
114 }
115 expect(ids[1]).toEqual(ids[0]);
116 });
117 });
118
119 describe("what it refuses, as the index's way does", () => {
120 for (const way of ["index", "fast-import"] as const) {
121 test(`${way}: a file where a directory is, a file under a file, and a moved branch`, async () => {
122 setCommitRoute(way);
123 const dir = await repo();
124 const first = unwrap(
125 await commitFiles(dir, {
126 branch: "main",
127 message: "m",
128 files: [
129 { path: "d/x.txt", content: "x" },
130 { path: "f.txt", content: "f" },
131 ],
132 author,
133 }),
134 );
135 const over = await commitFiles(dir, { branch: "main", message: "m", files: [{ path: "d", content: "file" }], author });
136 expect(over.ok ? undefined : over.error).toEqual({ kind: "path_conflict", path: "d" });
137 const under = await commitFiles(dir, { branch: "main", message: "m", files: [{ path: "f.txt/y", content: "y" }], author });
138 expect(under.ok ? undefined : under.error).toEqual({ kind: "path_conflict", path: "f.txt/y" });
139 const moved = await commitFiles(dir, {
140 branch: "main",
141 message: "m",
142 files: [{ path: "g", content: "g" }],
143 author,
144 expectTip: "0".repeat(40),
145 });
146 expect(moved.ok ? undefined : moved.error).toEqual({ kind: "branch_moved" });
147 // Nothing of the refused writes moved the branch.
148 expect(unwrap(await runGit(["rev-parse", "refs/heads/main"], { cwd: dir }))).toBe(first.commitOid);
149 });
150 }
151
152 test("a land that refuses leaves the branch where it was, and a land sees the commit first", async () => {
153 const dir = await repo();
154 const first = unwrap(await commitFiles(dir, { branch: "main", message: "m", files: [{ path: "a", content: "a" }], author }));
155 let seen: [string, string | undefined] | undefined;
156 const refused = await commitFiles(dir, {
157 branch: "main",
158 message: "m2",
159 files: [{ path: "b", content: "b" }],
160 author,
161 land: async (commitOid, tip) => {
162 seen = [commitOid, tip];
163 // The commit exists before the ref moves.
164 expect((await runGit(["cat-file", "-t", commitOid], { cwd: dir })).ok).toBe(true);
165 return { ok: false, error: "origin said no" };
166 },
167 });
168 expect(refused.ok ? undefined : refused.error).toEqual({ kind: "land_refused", message: "origin said no" });
169 expect(seen?.[1]).toBe(first.commitOid);
170 expect(unwrap(await runGit(["rev-parse", "refs/heads/main"], { cwd: dir }))).toBe(first.commitOid);
171 });
172 });
173
174 test("a commit is two git processes (fast-import and the update-ref), not six", async () => {
175 const dir = await repo();
176 unwrap(await commitFiles(dir, { branch: "main", message: "warm", files: [{ path: "a", content: "a" }], author }));
177 const write = (path: string) => async () => {
178 unwrap(
179 await commitFiles(dir, {
180 branch: "main",
181 message: path,
182 files: [
183 { path, content: path },
184 { path: `dir/${path}`, content: path },
185 ],
186 author,
187 }),
188 );
189 };
190 // The parent's paths are read through the repository's long-lived reader, opened once.
191 await gitSpawns(write("b"));
192 expect(await gitSpawns(write("c"))).toBe(2);
193 setCommitRoute("index");
194 expect(await gitSpawns(write("d"))).toBe(6);
195 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs