From d2c96d852357f365c532ec41142bc5c64593a69b Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:15:34 +0100 Subject: [PATCH 01/11] test: check unsafe vendor folders against unsafeVendor The e2e loop ran 14 spellings of an unsafe vendor folder through init, track, sync and a sync journal. unsafeVendor decides all of them, so the spellings now live in a unit table. e2e keeps the repo root (journal only), a sibling of the repo and .git, to show each command refuses and writes nothing. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 27 ++++++++------------------- test/units.test.ts | 30 ++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index c5bc3b32..6b7855f4 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -15060,21 +15060,10 @@ exec '${Bun.which("git")}' "$@" mkdirSync(join(t.tmp, "sibling")); writeFileSync(sentinelOf(t), "precious\n"); }; - const unsafeVendors: [string, (t: Case) => string, string][] = [ - ["the repo root", () => ".", "the repo root"], - ["the folder above the repo", () => "..", "is outside the repo"], - ["a sibling of the repo", () => "../sibling", "is outside the repo"], - ["an absolute path outside the repo", (t) => join(t.tmp, "sibling"), "is outside the repo"], - ["the patchbook", () => ".patchbook", "is inside .patchbook"], - ["a folder in the patchbook", () => ".patchbook/vendor", "is inside .patchbook"], - ["the patchbook in title case", () => ".Patchbook", "is inside .patchbook"], - ["the patchbook in capitals", () => ".PATCHBOOK", "is inside .patchbook"], - ["a folder in the patchbook in capitals", () => ".PATCHBOOK/vendor", "is inside .patchbook"], - ["the git dir", () => ".git", "is inside .git"], - ["a folder in the git dir", () => "lib/.GIT/vendor", "is inside .git"], - ["a name HFS reads as git", () => ".g\u200cit", "is inside .git"], - ["the NTFS short name of git", () => "git~1", "is inside .git"], - ["a name NTFS reads as git", () => ".git.", "is inside .git"], + const unsafeVendors: [string, string, string][] = [ + ["the repo root", ".", "the repo root"], + ["a sibling of the repo", "../sibling", "is outside the repo"], + ["the git dir", ".git", "is inside .git"], ]; for (const [what, vendor, why] of unsafeVendors) { @@ -15086,7 +15075,7 @@ exec '${Bun.which("git")}' "$@" repo.write("README.md", "mine\n"); repo.commit("start"); const before = tree(repo.path); - const out = t.pb(["init", "--upstream", t.up.path, "--output-to", "out", "--vendor", vendor(t)], { cwd: repo.path, code: 1 }); + const out = t.pb(["init", "--upstream", t.up.path, "--output-to", "out", "--vendor", vendor], { cwd: repo.path, code: 1 }); expect(out.stderr).toContain(why); expect(out.stderr).not.toContain("EINVAL"); expect(existsSync(join(repo.path, ".git"))).toBe(true); @@ -15107,7 +15096,7 @@ exec '${Bun.which("git")}' "$@" const config = join(t.repo.path, ".patchbook/config.toml"); const configBefore = read(config); const before = tree(t.repo.path); - const out = t.pb(["track", "extra", extra.path, "--vendor", vendor(t)], { cwd: t.repo.path, code: 1 }); + const out = t.pb(["track", "extra", extra.path, "--vendor", vendor], { cwd: t.repo.path, code: 1 }); expect(out.stderr).toContain(why); expect(out.stderr).not.toContain("EINVAL"); expect(existsSync(join(t.repo.path, ".git"))).toBe(true); @@ -15124,7 +15113,7 @@ exec '${Bun.which("git")}' "$@" extra.commit("a"); t.pb(["track", "extra", extra.path, "--vendor", "vendor/extra"], { cwd: t.repo.path }); const config = join(t.repo.path, ".patchbook/config.toml"); - writeFileSync(config, read(config).replaceAll('vendor = "vendor/extra"', `vendor = ${JSON.stringify(vendor(t))}`)); + writeFileSync(config, read(config).replaceAll('vendor = "vendor/extra"', `vendor = ${JSON.stringify(vendor)}`)); const before = tree(t.repo.path); const out = t.pb(["sync", "extra"], { cwd: t.repo.path, code: 1 }); expect(out.stderr).toContain(why); @@ -15144,7 +15133,7 @@ exec '${Bun.which("git")}' "$@" const journal = join(t.repo.path, ".patchbook/sync-extra"); mkdirSync(join(journal, "old"), { recursive: true }); writeFileSync(join(journal, "old/planted.txt"), "from the journal\n"); - const record = { from: `${pin.commit} ${pin.tree}`, to: "", rewrite: true, added: "", vendor: vendor(t), copy: false, made: "" }; + const record = { from: `${pin.commit} ${pin.tree}`, to: "", rewrite: true, added: "", vendor, copy: false, made: "" }; writeFileSync(join(journal, "pin"), JSON.stringify(record)); const before = tree(t.repo.path); const out = t.pb(["sync", "extra"], { cwd: t.repo.path, code: 1 }); diff --git a/test/units.test.ts b/test/units.test.ts index 8fc9cc21..394ebed4 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -1,7 +1,7 @@ import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; +import { dirname, join, resolve } from "node:path"; import type { LastSync, Problem, SyncReport } from "../src/api.ts"; import type { Assembly } from "../src/assemble.ts"; import type { Reserved } from "../src/book.ts"; @@ -15,7 +15,7 @@ process.env["XDG_CONFIG_HOME"] = join(sandbox, "config"); const { applyStructure, describe: describeProblem, parseBuildLock } = await import("../src/assemble.ts"); const { blockHash, blocksOf, blockSpans, checkEntry, formatEntry, nearest, parsePlaceholders, readEntries, Rules } = await import("../src/blocks.ts"); -const { Book, globRe, lockText, parseLock } = await import("../src/book.ts"); +const { Book, globRe, lockText, parseLock, unsafeVendor } = await import("../src/book.ts"); const { Change, editText, formatChange, parseChange } = await import("../src/changes.ts"); const { changeParts, intentFromEdits, intentFromParagraph, intentSettings, listDiffs, nameFromEdits, pendingParts, PROVIDERS, writeIntents } = await import("../src/intent.ts"); const { Fail } = await import("../src/lib/fail.ts"); @@ -2063,3 +2063,29 @@ describe("classify", () => { .toMatchObject([{ kind: "delete-upstream", path: "a/SKILL.md" }, { kind: "add", path: "b/SKILL.md" }, { kind: "delete-upstream", path: "c/SKILL.md" }]); }); }); + +describe("unsafeVendor", () => { + const root = scratch(); + + test.each([ + ["the repo root", ".", "is the repo root"], + ["the folder above the repo", "..", "is outside the repo"], + ["a sibling of the repo", "../sibling", "is outside the repo"], + ["an absolute path outside the repo", "/elsewhere/vendor", "is outside the repo"], + ["the patchbook", ".patchbook", "is inside .patchbook"], + ["a folder in the patchbook", ".patchbook/vendor", "is inside .patchbook"], + ["the patchbook in title case", ".Patchbook", "is inside .patchbook"], + ["the patchbook in capitals", ".PATCHBOOK", "is inside .patchbook"], + ["a folder in the patchbook in capitals", ".PATCHBOOK/vendor", "is inside .patchbook"], + ["the git dir", ".git", "is inside .git"], + ["a folder in the git dir", "lib/.GIT/vendor", "is inside .git"], + ["a name HFS reads as git", ".g\u200cit", "is inside .git"], + ["the NTFS short name of git", "git~1", "is inside .git"], + ["a name NTFS reads as git", ".git.", "is inside .git"], + ["a folder in the repo", "vendor/extra", null], + ["a name that only starts like the patchbook", ".patchbookx", null], + ["a name that only starts like git", "lib/.gitx", null], + ] as const)("a vendored copy at %s", (_what, vendor, why) => { + expect(unsafeVendor(root, resolve(root, vendor))).toBe(why); + }); +}); From 923c18ae8f8e38fc77faadafe9f4db2544f4e925 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:16:11 +0100 Subject: [PATCH 02/11] test: check nested git spellings against refuseNestedGit init, track and sync each ran five kinds of nested git dir through the CLI. refuseNestedGit decides which names count, so the spellings now live in a unit table. e2e keeps a repo of its own and a linked worktree, the two a user makes with git itself. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 13 ------------- test/units.test.ts | 24 +++++++++++++++++++++++- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 6b7855f4..3a5dc4af 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -15324,19 +15324,6 @@ exec '${Bun.which("git")}' "$@" sh(["git", "init", "-q", "-b", "main", join(repo.path, "lib")], { cwd: repo.path }); writeFileSync(join(repo.path, "lib/wip.txt"), "uncommitted\n"); }], - ["a git file deeper down", "lib", "lib/sub/.git", (repo) => { - mkdirSync(join(repo.path, "lib/sub"), { recursive: true }); - writeFileSync(join(repo.path, "lib/sub/.git"), gitFile); - writeFileSync(join(repo.path, "lib/sub/wip.txt"), "uncommitted\n"); - }], - ["a git dir in capitals", "lib", "lib/.GIT", (repo) => { - mkdirSync(join(repo.path, "lib/.GIT"), { recursive: true }); - writeFileSync(join(repo.path, "lib/.GIT/HEAD"), "ref: refs/heads/main\n"); - }], - ["a git dir HFS reads as git", "lib", "lib/.g\u200cit", (repo) => { - mkdirSync(join(repo.path, "lib/.g\u200cit"), { recursive: true }); - writeFileSync(join(repo.path, "lib/.g\u200cit/HEAD"), "ref: refs/heads/main\n"); - }], ["a linked worktree", "wt", "wt/.git", (repo) => { sh(["git", "worktree", "add", "-q", "--detach", join(repo.path, "wt"), "HEAD"], { cwd: repo.path }); writeFileSync(join(repo.path, "wt/wip2.txt"), "uncommitted\n"); diff --git a/test/units.test.ts b/test/units.test.ts index 394ebed4..fcccf3c3 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -15,7 +15,7 @@ process.env["XDG_CONFIG_HOME"] = join(sandbox, "config"); const { applyStructure, describe: describeProblem, parseBuildLock } = await import("../src/assemble.ts"); const { blockHash, blocksOf, blockSpans, checkEntry, formatEntry, nearest, parsePlaceholders, readEntries, Rules } = await import("../src/blocks.ts"); -const { Book, globRe, lockText, parseLock, unsafeVendor } = await import("../src/book.ts"); +const { Book, globRe, lockText, parseLock, refuseNestedGit, unsafeVendor } = await import("../src/book.ts"); const { Change, editText, formatChange, parseChange } = await import("../src/changes.ts"); const { changeParts, intentFromEdits, intentFromParagraph, intentSettings, listDiffs, nameFromEdits, pendingParts, PROVIDERS, writeIntents } = await import("../src/intent.ts"); const { Fail } = await import("../src/lib/fail.ts"); @@ -2089,3 +2089,25 @@ describe("unsafeVendor", () => { expect(unsafeVendor(root, resolve(root, vendor))).toBe(why); }); }); + +describe("refuseNestedGit", () => { + const rows: [string, (lib: string) => void, string | null][] = [ + ["a git dir", (lib) => mkdirSync(join(lib, ".git")), "lib/.git"], + ["a git file deeper down", (lib) => put(join(lib, "sub/.git"), "gitdir: ../elsewhere\n"), "lib/sub/.git"], + ["a git dir in capitals", (lib) => put(join(lib, ".GIT/HEAD"), "ref: refs/heads/main\n"), "lib/.GIT"], + ["a git dir HFS reads as git", (lib) => put(join(lib, ".g\u200cit/HEAD"), "ref: refs/heads/main\n"), "lib/.g\u200cit"], + ["a git dir NTFS reads as git", (lib) => mkdirSync(join(lib, "a/git~1"), { recursive: true }), "lib/a/git~1"], + ["a folder that only starts like git", (lib) => put(join(lib, ".gitx/HEAD"), "ref: refs/heads/main\n"), null], + ["plain files", (lib) => put(join(lib, "sub/a.md"), "a\n"), null], + ]; + + test.each(rows)("a vendor folder that holds %s", (_what, make, found) => { + const root = scratch(); + const lib = join(root, "lib"); + mkdirSync(lib); + make(lib); + const check = () => refuseNestedGit(root, "extra", lib); + if (found === null) expect(check).not.toThrow(); + else expect(check).toThrow(`the vendored copy of extra (lib) holds ${found}, a git repo of its own.`); + }); +}); From ccac7b7e2c0186604d53e5d0430cf3decc0422c9 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:16:46 +0100 Subject: [PATCH 03/11] test: merge the three output folder .git loops into one table Three loops ran build --force and status for an output folder that git reads as .git, with the same body and the same expected message. They are now rows of one table. The same 13 cases run. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 31 +++++-------------------------- 1 file changed, 5 insertions(+), 26 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 3a5dc4af..bfffb054 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -14639,19 +14639,6 @@ exec '${Bun.which("git")}' "$@" }); } - for (const to of ["skills/.git", "a/b/.git/c"]) { - vendorTest(`output folder ${to} has a git segment and is rejected`, (t) => { - t.missingScaffoldPatchBuild(); - setOutputFolder(t, to); - const before = tree(t.repo.path); - for (const args of [["build", "--force"], ["status"]]) { - const out = t.pb(args, { cwd: t.repo.path, code: 1 }); - expect(out.stderr).toContain("inside .git"); - expect(tree(t.repo.path)).toEqual(before); - } - }); - } - test("track rejects a mount that puts the output under a git folder in the folder layout", () => { const t = new Case(); try { @@ -14760,19 +14747,6 @@ exec '${Bun.which("git")}' "$@" expect(tree(t.repo.path)).toEqual(before); }); - for (const to of [".GIT", ".Git/x", "out/.gIT/y"]) { - vendorTest(`output folder ${to} has a git segment in another case and is rejected`, (t) => { - t.missingScaffoldPatchBuild(); - setOutputFolder(t, to); - const before = tree(t.repo.path); - for (const args of [["build", "--force"], ["status"]]) { - const out = t.pb(args, { cwd: t.repo.path, code: 1 }); - expect(out.stderr).toContain("inside .git"); - expect(tree(t.repo.path)).toEqual(before); - } - }); - } - const readsAsDotPatchbook = [ [".PATCHBOOK", ".PATCHBOOK"], [".Patchbook/x", ".Patchbook/x"], @@ -14807,6 +14781,11 @@ exec '${Bun.which("git")}' "$@" }); const gitReadsAsDotGit = [ + [".git as a folder", "skills/.git"], + [".git above a folder", "a/b/.git/c"], + [".GIT", ".GIT"], + [".Git above a folder", ".Git/x"], + [".gIT in a folder", "out/.gIT/y"], [".git.", ".git."], [".git and a space", ".git "], ["GIT~1", "GIT~1"], From 084d140ead59bf7d4e140023fb747e6b31f73c14 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:17:22 +0100 Subject: [PATCH 04/11] test: check output folders git reads as .git against Book.fromText Every command that reads the config builds the Book through Book.fromText, which refuses an output folder git reads as .git. The 13 spellings, and 6 names that only look like .git, now run there as a unit table. e2e keeps skills/.git and .git. to show build --force and status refuse and leave the repo as it was. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 11 ----------- test/units.test.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index bfffb054..e0c4d0d8 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -14782,18 +14782,7 @@ exec '${Bun.which("git")}' "$@" const gitReadsAsDotGit = [ [".git as a folder", "skills/.git"], - [".git above a folder", "a/b/.git/c"], - [".GIT", ".GIT"], - [".Git above a folder", ".Git/x"], - [".gIT in a folder", "out/.gIT/y"], [".git.", ".git."], - [".git and a space", ".git "], - ["GIT~1", "GIT~1"], - [".git:x", "out/.git:x"], - ["a backslash before .git", "out/a\\.git"], - ["a byte order mark before .GIT", "out/\ufeff.GIT/y"], - [".git then the noncharacter U+FFFE", ".git\ufffe"], - [".GIT with a zero-width non-joiner and U+FFFF", "out/.GIT\u200c\uffffx/y"], ] as const; for (const [what, to] of gitReadsAsDotGit) { diff --git a/test/units.test.ts b/test/units.test.ts index fcccf3c3..7a645fa4 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -2111,3 +2111,30 @@ describe("refuseNestedGit", () => { else expect(check).toThrow(`the vendored copy of extra (lib) holds ${found}, a git repo of its own.`); }); }); + +describe("an output git reads as .git", () => { + const upstream = (name: string, mount: string) => `[[upstream]]\nname = "${name}"\nremote = "https://example.com/${name}.git"\nmount = ${JSON.stringify(mount)}\n`; + const folder = (to: string) => Book.fromText(scratch(), `layout = "folder"\n[output]\nto = ${JSON.stringify(to)}\n${upstream("up", "")}`); + + test.each([ + [".git as a folder", "skills/.git"], + [".git above a folder", "a/b/.git/c"], + [".GIT", ".GIT"], + [".Git above a folder", ".Git/x"], + [".gIT in a folder", "out/.gIT/y"], + [".git.", ".git."], + [".git and a space", ".git "], + ["GIT~1", "GIT~1"], + [".git:x", "out/.git:x"], + ["a backslash before .git", "out/a\\.git"], + ["a byte order mark before .GIT", "out/\ufeff.GIT/y"], + [".git then the noncharacter U+FFFE", ".git\ufffe"], + [".GIT with a zero-width non-joiner and U+FFFF", "out/.GIT\u200c\uffffx/y"], + ])("refuses [output] to %s", async (_what, to) => { + await expect(folder(to)).rejects.toThrow("inside .git"); + }); + + test.each([".gitx", "git~2", ".git.x", "a.git", ".git\u200c.", ".git\ufffd"])("takes [output] to %p", async (to) => { + await expect(folder(to)).resolves.toBeInstanceOf(Book); + }); +}); From 2849e25645df7d41a7e573fa8c84e47339e72660 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:17:38 +0100 Subject: [PATCH 05/11] test: merge the track mount case-folding test into the .git names test "track rejects a mount with a git segment in another case in both layouts" had the same setup and assertions as "init and track reject names git reads as .git in both layouts". Its three mounts are now rows of the latter. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 31 +------------------------------ 1 file changed, 1 insertion(+), 30 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index e0c4d0d8..04fccd83 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -14830,7 +14830,7 @@ exec '${Bun.which("git")}' "$@" for (const cwd of [folder.path, join(t.tmp, "fork")]) { const config = join(cwd, ".patchbook/config.toml"); const before = { config: read(config), tree: tree(cwd) }; - for (const mount of [".git.", "a/.git ", "GIT~1/x", "a/.g\u200cit"]) { + for (const mount of [".git.", "a/.git ", "GIT~1/x", "a/.g\u200cit", ".GIT/x", "a/.Git", "./.gIt/x"]) { const tracked = t.pb(["track", "m", more.path, "--mount", mount], { cwd, code: 1 }); expect(tracked.stderr).toContain("inside .git"); expect(read(config)).toBe(before.config); @@ -14874,35 +14874,6 @@ exec '${Bun.which("git")}' "$@" } }, TIMEOUT); - test("track rejects a mount with a git segment in another case in both layouts", () => { - const t = new Case(); - try { - const up = new Repo(join(t.tmp, "upstream")); - up.write("a.md", "a\n"); - up.commit("start"); - const more = new Repo(join(t.tmp, "more")); - more.write("d/m.md", "m\n"); - more.commit("start"); - const folder = new Repo(join(t.tmp, "adapted")); - folder.write("README.md", "mine\n"); - folder.commit("start"); - t.pb(["init", "--upstream", up.path, "--output-to", "out"], { cwd: folder.path }); - t.pb(["clone", up.path, "fork"], { cwd: t.tmp }); - for (const cwd of [folder.path, join(t.tmp, "fork")]) { - const config = join(cwd, ".patchbook/config.toml"); - const before = { config: read(config), tree: tree(cwd) }; - for (const mount of [".GIT/x", "a/.Git", "./.gIt/x"]) { - const tracked = t.pb(["track", "m", more.path, "--mount", mount], { cwd, code: 1 }); - expect(tracked.stderr).toContain("inside .git"); - expect(read(config)).toBe(before.config); - expect(tree(cwd)).toEqual(before.tree); - } - } - } finally { - t.cleanup(); - } - }, TIMEOUT); - vendorTest("an absolute output folder reached through a link above the repo builds twice", (t) => { symlinkSync(t.tmp, join(t.tmp, "via")); const config = join(t.repo.path, ".patchbook/config.toml"); From 7281d963c47fe2724ca84e3ffa8648d5835447b8 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:18:18 +0100 Subject: [PATCH 06/11] test: check mounts git reads as .git against Book.fromText track builds the new config through Book.fromText, which refuses a mount git reads as .git in both layouts. The seven mount spellings now run there as unit rows, and init's three --output-to spellings were already rows of the [output] to table. e2e keeps .git. for init and .git. and .GIT/x for track in each layout. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 4 ++-- test/units.test.ts | 8 +++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 04fccd83..85355bfa 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -14820,7 +14820,7 @@ exec '${Bun.which("git")}' "$@" const folder = new Repo(join(t.tmp, "adapted")); folder.write("README.md", "mine\n"); folder.commit("start"); - for (const to of [".git.", ".git ", "GIT~1"]) { + for (const to of [".git."]) { const out = t.pb(["init", "--upstream", up.path, "--output-to", to], { cwd: folder.path, code: 1 }); expect(out.stderr).toContain("inside .git"); expect(existsSync(join(folder.path, ".patchbook"))).toBe(false); @@ -14830,7 +14830,7 @@ exec '${Bun.which("git")}' "$@" for (const cwd of [folder.path, join(t.tmp, "fork")]) { const config = join(cwd, ".patchbook/config.toml"); const before = { config: read(config), tree: tree(cwd) }; - for (const mount of [".git.", "a/.git ", "GIT~1/x", "a/.g\u200cit", ".GIT/x", "a/.Git", "./.gIt/x"]) { + for (const mount of [".git.", ".GIT/x"]) { const tracked = t.pb(["track", "m", more.path, "--mount", mount], { cwd, code: 1 }); expect(tracked.stderr).toContain("inside .git"); expect(read(config)).toBe(before.config); diff --git a/test/units.test.ts b/test/units.test.ts index 7a645fa4..cbdf63a9 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -2114,7 +2114,8 @@ describe("refuseNestedGit", () => { describe("an output git reads as .git", () => { const upstream = (name: string, mount: string) => `[[upstream]]\nname = "${name}"\nremote = "https://example.com/${name}.git"\nmount = ${JSON.stringify(mount)}\n`; - const folder = (to: string) => Book.fromText(scratch(), `layout = "folder"\n[output]\nto = ${JSON.stringify(to)}\n${upstream("up", "")}`); + const folder = (to: string, more = "") => Book.fromText(scratch(), `layout = "folder"\n[output]\nto = ${JSON.stringify(to)}\n${upstream("up", "")}${more}`); + const fork = (more: string) => Book.fromText(scratch(), upstream("up", "") + more); test.each([ [".git as a folder", "skills/.git"], @@ -2137,4 +2138,9 @@ describe("an output git reads as .git", () => { test.each([".gitx", "git~2", ".git.x", "a.git", ".git\u200c.", ".git\ufffd"])("takes [output] to %p", async (to) => { await expect(folder(to)).resolves.toBeInstanceOf(Book); }); + + test.each([".git.", "a/.git ", "GIT~1/x", "a/.g\u200cit", ".GIT/x", "a/.Git", "./.gIt/x"])("refuses a second upstream mounted at %p in either layout", async (mount) => { + await expect(fork(upstream("m", mount))).rejects.toThrow("inside .git"); + await expect(folder("out", upstream("m", mount))).rejects.toThrow("inside .git"); + }); }); From 4594ed2e3bc3aebc8aaaaa1fd0c7864beb3cb590 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:19:11 +0100 Subject: [PATCH 07/11] test: check folded .patchbook upstream paths against refuseFoldedUpstream clone, init, sync and check each ran three spellings of a folder that macOS or Windows reads as .patchbook. refuseFoldedUpstream decides them, so seven refused and four allowed paths now run there as a unit table. e2e keeps .PATCHBOOK for each command. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 98 +++++++++++++++++++++------------------------- test/units.test.ts | 15 ++++++- 2 files changed, 59 insertions(+), 54 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 85355bfa..eb68a6c8 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -2135,65 +2135,57 @@ test("clone of a patchbook repo starts a patchbook of its own", () => { } }, TIMEOUT); -const foldedUpstream = [ - [".PATCHBOOK", ".PATCHBOOK/config.toml"], - [".patchbook.", ".patchbook./z.txt"], - [".patchbook and a space", ".patchbook /w.txt"], -] as const; +const folded = ".PATCHBOOK/config.toml"; const cantFork = "patchbook can't fork an upstream with a folder that is .patchbook on macOS and Windows"; -for (const [what, path] of foldedUpstream) { - test(`clone refuses an upstream with a ${what} folder and writes nothing`, () => { - const t = new Case(); - try { - const up = new Repo(join(t.tmp, "upstream")); - up.write("app.txt", "one\n"); - up.write(path, "upstream = true\n"); - up.commit("start"); - const refused = t.pb(["clone", up.path, "fork"], { cwd: t.tmp, code: 1 }); - expect(refused.stderr).toContain(path); - expect(refused.stderr).toContain(cantFork); - expect(existsSync(join(t.tmp, "fork"))).toBe(false); - } finally { - t.cleanup(); - } - }, TIMEOUT); +test("clone refuses an upstream with a .PATCHBOOK folder and writes nothing", () => { + const t = new Case(); + try { + const up = new Repo(join(t.tmp, "upstream")); + up.write("app.txt", "one\n"); + up.write(folded, "upstream = true\n"); + up.commit("start"); + const refused = t.pb(["clone", up.path, "fork"], { cwd: t.tmp, code: 1 }); + expect(refused.stderr).toContain(folded); + expect(refused.stderr).toContain(cantFork); + expect(existsSync(join(t.tmp, "fork"))).toBe(false); + } finally { + t.cleanup(); + } +}, TIMEOUT); - test(`init refuses an upstream with a ${what} folder and writes nothing`, () => { - const t = new Case(); - try { - const leaf = path.replace("config.toml", "notes.md"); - const up = new Repo(join(t.tmp, "upstream")); - up.write("app.txt", "one\n"); - up.write(leaf, "upstream = true\n"); - up.commit("start"); - const mine = forkOf(t, up); - const before = tree(mine.path); - const refused = t.pb(["init", "--upstream", up.path], { cwd: mine.path, code: 1 }); - expect(refused.stderr).toContain(leaf); - expect(refused.stderr).toContain(cantFork); - expect(tree(mine.path)).toEqual(before); - } finally { - t.cleanup(); - } - }, TIMEOUT); +test("init refuses an upstream with a .PATCHBOOK folder and writes nothing", () => { + const t = new Case(); + try { + const leaf = folded.replace("config.toml", "notes.md"); + const up = new Repo(join(t.tmp, "upstream")); + up.write("app.txt", "one\n"); + up.write(leaf, "upstream = true\n"); + up.commit("start"); + const mine = forkOf(t, up); + const before = tree(mine.path); + const refused = t.pb(["init", "--upstream", up.path], { cwd: mine.path, code: 1 }); + expect(refused.stderr).toContain(leaf); + expect(refused.stderr).toContain(cantFork); + expect(tree(mine.path)).toEqual(before); + } finally { + t.cleanup(); + } +}, TIMEOUT); - forkTest(`sync and check refuse an upstream that gains a ${what} folder and write nothing`, (t) => { - t.up.write(path, "upstream = true\n"); - t.up.commit("upstream gains a folded folder"); - const before = tree(t.fork.path); - for (const args of [["sync"], ["check"]]) { - const refused = t.pb(args, { cwd: t.fork.path, code: 1 }); - expect(refused.stderr).toContain(path); - expect(refused.stderr).toContain(cantFork); - expect(tree(t.fork.path)).toEqual(before); - } - }); -} +forkTest("sync and check refuse an upstream that gains a .PATCHBOOK folder and write nothing", (t) => { + t.up.write(folded, "upstream = true\n"); + t.up.commit("upstream gains a folded folder"); + const before = tree(t.fork.path); + for (const args of [["sync"], ["check"]]) { + const refused = t.pb(args, { cwd: t.fork.path, code: 1 }); + expect(refused.stderr).toContain(folded); + expect(refused.stderr).toContain(cantFork); + expect(tree(t.fork.path)).toEqual(before); + } +}); describe("a fork that already holds a folder read as .patchbook", () => { - const folded = ".PATCHBOOK/config.toml"; - const refusedEverywhere = (t: ForkCase, hand: () => void) => { hand(); const files = tree(t.fork.path); diff --git a/test/units.test.ts b/test/units.test.ts index cbdf63a9..1f21b3cc 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -15,7 +15,7 @@ process.env["XDG_CONFIG_HOME"] = join(sandbox, "config"); const { applyStructure, describe: describeProblem, parseBuildLock } = await import("../src/assemble.ts"); const { blockHash, blocksOf, blockSpans, checkEntry, formatEntry, nearest, parsePlaceholders, readEntries, Rules } = await import("../src/blocks.ts"); -const { Book, globRe, lockText, parseLock, refuseNestedGit, unsafeVendor } = await import("../src/book.ts"); +const { Book, globRe, lockText, parseLock, refuseFoldedUpstream, refuseNestedGit, unsafeVendor } = await import("../src/book.ts"); const { Change, editText, formatChange, parseChange } = await import("../src/changes.ts"); const { changeParts, intentFromEdits, intentFromParagraph, intentSettings, listDiffs, nameFromEdits, pendingParts, PROVIDERS, writeIntents } = await import("../src/intent.ts"); const { Fail } = await import("../src/lib/fail.ts"); @@ -2144,3 +2144,16 @@ describe("an output git reads as .git", () => { await expect(folder("out", upstream("m", mount))).rejects.toThrow("inside .git"); }); }); + +describe("refuseFoldedUpstream", () => { + test.each([".PATCHBOOK/config.toml", ".Patchbook/x", ".patchbook./z.txt", ".patchbook /w.txt", ".PATCHBOOK. . /y", ".patchbook:x/y", ".patchbook\\x"])( + "refuses an upstream that holds %p", + (path) => { + expect(() => refuseFoldedUpstream(["app.txt", path])).toThrow(`upstream has ${path}, which is .patchbook on macOS and Windows.`); + }, + ); + + test.each([".patchbook/config.toml", ".patchbookx/a", ".patchbook.x/a", "x/.PATCHBOOK/a"])("takes an upstream that holds %p", (path) => { + expect(() => refuseFoldedUpstream(["app.txt", path])).not.toThrow(); + }); +}); From 808966ffefa99386ac9c8f21a0a90495083de58b Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:19:40 +0100 Subject: [PATCH 08/11] test: check folded .patchbook output paths against reservedOutput The commit hook refuses a staged file the Book reserves, and Book.reservedOutput decides which paths those are. The three spellings the hook test looped over now run there with more rows. e2e keeps .patchbook./x.md, which runs on every file system, to show the hook refuses the commit and changes nothing. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 34 ++++++++++++++-------------------- test/units.test.ts | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index eb68a6c8..012584f7 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -5771,26 +5771,20 @@ describe("ForkTest", () => { } } - for (const [what, path, test] of [ - [".PATCHBOOK", ".PATCHBOOK/x.md", forkTestOnCaseSensitiveFs], - [".patchbook.", ".patchbook./x.md", forkTest], - [".patchbook and a space", ".patchbook /x.md", forkTest], - ] as const) { - test(`hook refuses a staged file under ${what} before recording it`, (t) => { - const place = ".patchbook"; - t.fork.write(path, "ours\n"); - sh(["git", "add", "--", path], { cwd: t.fork.path }); - const files = tree(t.fork.path); - const state = gitState(t); - const refused = intoKeptCommit(t, "--allow-empty"); - expect(refused.code).toBe(1); - expect(refused.stderr).toContain(`patchbook: refusing this commit: ${path} is new, but a change can't write into ${place}.`); - expect(refused.stderr).toContain(`Move ${path} out of there, or skip the hook once with PATCHBOOK_HOOK=0.`); - expect(tree(t.fork.path)).toEqual(files); - expect(gitState(t)).toBe(state); - expect(existsSync(join(t.fork.path, ".patchbook/changes"))).toBe(false); - }); - } + forkTest("hook refuses a staged file under .patchbook. before recording it", (t) => { + const path = ".patchbook./x.md"; + t.fork.write(path, "ours\n"); + sh(["git", "add", "--", path], { cwd: t.fork.path }); + const files = tree(t.fork.path); + const state = gitState(t); + const refused = intoKeptCommit(t, "--allow-empty"); + expect(refused.code).toBe(1); + expect(refused.stderr).toContain(`patchbook: refusing this commit: ${path} is new, but a change can't write into .patchbook.`); + expect(refused.stderr).toContain(`Move ${path} out of there, or skip the hook once with PATCHBOOK_HOOK=0.`); + expect(tree(t.fork.path)).toEqual(files); + expect(gitState(t)).toBe(state); + expect(existsSync(join(t.fork.path, ".patchbook/changes"))).toBe(false); + }); forkTestOnCaseSensitiveFs("hook leaves an untracked file under .GIT out of the commit", (t) => { t.fork.write("a/.GIT/y", "ours\n"); diff --git a/test/units.test.ts b/test/units.test.ts index 1f21b3cc..d7c64d6f 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -2157,3 +2157,22 @@ describe("refuseFoldedUpstream", () => { expect(() => refuseFoldedUpstream(["app.txt", path])).not.toThrow(); }); }); + +describe("reservedOutput", () => { + const fork = () => Book.fromText(scratch(), `[[upstream]]\nremote = "https://example.com/x.git"\nmount = ""\n`); + + test.each([ + [".PATCHBOOK/x.md", ".patchbook"], + [".patchbook./x.md", ".patchbook"], + [".patchbook /x.md", ".patchbook"], + [".patchbook:x/y.md", ".patchbook"], + ["a/.git./x.md", ".git"], + ["a/.GIT/x.md", ".git"], + ])("refuses a change that writes %p, which is in %p", async (path, place) => { + expect((await fork()).reservedOutput(path)).toEqual({ place, refuse: true }); + }); + + test.each(["app.txt", ".patchbookx/x.md", "a/.PATCHBOOK/x.md", "a/.gitx/x.md"])("lets a change write %p", async (path) => { + expect((await fork()).reservedOutput(path)).toBeNull(); + }); +}); From 0712f812eb6a36f43c978b4d15ef8a41a80b85bc Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:20:15 +0100 Subject: [PATCH 09/11] test: check edit paths that leave the tree against parseChange 16 edit lines with a climbing, absolute, empty-segment or backslash path each ran status, status --json and build --force through the CLI. parseChange holds and refuses them, so the lines now run there as a unit table. e2e keeps an add and a copy that climb out of the repo, to show status reports them and build writes nothing inside or outside. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 14 -------------- test/units.test.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 012584f7..03ff26ac 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -5904,21 +5904,7 @@ describe("ForkTest", () => { const escaping = [ ["add climbing out", "add ../outside.txt"], - ["add absolute", "add /outside.txt"], ["copy dest climbing out", "copy app.txt -> ../copied.txt"], - ["copy source climbing out", "copy ../app.txt -> copied.txt"], - ["copy dest ./.patchbook/config.toml", "copy app.txt -> ./.patchbook/config.toml"], - ["add ./.patchbook/new.md", "add ./.patchbook/new.md"], - ["delete docs//guide.md", "delete docs//guide.md"], - ["add climbing out with a backslash", "add ..\\outside.txt"], - ["add backslash in a name", "add docs\\new.md"], - ["replace backslash", "replace docs\\guide.md"], - ["delete backslash", "delete docs\\guide.md"], - ["file backslash", "file docs\\guide.md"], - ["copy source backslash", "copy docs\\guide.md -> copied.md"], - ["copy dest backslash", "copy app.txt -> docs\\copied.md"], - ["copy dest .patchbook backslash config.toml", "copy app.txt -> .patchbook\\config.toml"], - ["move dest with a leading backslash", "move docs/guide.md -> \\guide.md"], ] as const; for (const [name, edit] of escaping) { forkTest(`${name} is invalid and nothing is read or written outside`, (t) => { diff --git a/test/units.test.ts b/test/units.test.ts index d7c64d6f..ab4b63ee 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -2176,3 +2176,31 @@ describe("reservedOutput", () => { expect((await fork()).reservedOutput(path)).toBeNull(); }); }); + +describe("an edit whose path leaves the tree", () => { + test.each([ + "add ../outside.txt", + "add /outside.txt", + "copy app.txt -> ../copied.txt", + "copy ../app.txt -> copied.txt", + "copy app.txt -> ./.patchbook/config.toml", + "add ./.patchbook/new.md", + "delete docs//guide.md", + "add ..\\outside.txt", + "add docs\\new.md", + "replace docs\\guide.md", + "delete docs\\guide.md", + "file docs\\guide.md", + "copy docs\\guide.md -> copied.md", + "copy app.txt -> docs\\copied.md", + "copy app.txt -> .patchbook\\config.toml", + "move docs/guide.md -> \\guide.md", + ])("is held and refused: %p", (edit) => { + const path = put(join(scratch(), "esc", "CHANGE.md"), `# esc\n\nintent: Reach outside.\n\nedits:\n- ${edit}\n`); + const refused: [string, string][] = []; + const change = parseChange(path, (line, detail) => refused.push([line, detail])); + expect(change.edits).toEqual([]); + expect(change.held).toEqual([`- ${edit}`]); + expect(refused).toEqual([[edit, expect.stringContaining("must be a path inside the tree: not absolute, with no empty, . or .. segment")]]); + }); +}); From ecfae1bf32a1f380996db0337bcb0448739c5248 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:20:38 +0100 Subject: [PATCH 10/11] test: drop the config.toml rows of the init link loop Its config.toml rows linked .patchbook/config.toml to a missing file and checked init refuses it in each layout. "init refuses a dangling link at .patchbook/config.toml and writes nothing" does the same in both layouts and also checks the repo is unchanged. The loop keeps upstream.lock and retired.md, which link to a file that exists. The rest of the table stays in e2e: refuseDanglingLinks and the checks in cmdInit are private to cli.ts. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 03ff26ac..4f13d6f8 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -3238,7 +3238,7 @@ test("init refuses a series that is a link", () => { }, TIMEOUT); for (const layout of ["fork", "folder"] as const) { - for (const name of ["config.toml", "upstream.lock", "retired.md"]) { + for (const name of ["upstream.lock", "retired.md"]) { test(`a ${layout} init refuses a ${name} that is a link`, () => { const t = new Case(); try { @@ -3248,13 +3248,13 @@ for (const layout of ["fork", "folder"] as const) { const fork = forkOf(t, up); const output = layout === "folder" ? ["--output-from", "", "--output-to", "out"] : []; const outside = join(t.tmp, name); - if (name !== "config.toml") writeFileSync(outside, "mine\n"); + writeFileSync(outside, "mine\n"); mkdirSync(join(fork.path, ".patchbook")); symlinkSync(outside, join(fork.path, ".patchbook", name)); const out = t.pb(["init", "--upstream", up.path, ...output], { cwd: fork.path, code: 1 }); - const refusal = { "config.toml": "is a symlink to a missing file", "upstream.lock": "is a link", "retired.md": "already exists" }[name]; + const refusal = { "upstream.lock": "is a link", "retired.md": "already exists" }[name]; expect(out.stderr).toContain(`.patchbook/${name} ${refusal}`); - expect(existsSync(outside) ? read(outside) : null).toBe(name === "config.toml" ? null : "mine\n"); + expect(read(outside)).toBe("mine\n"); } finally { t.cleanup(); } From a37b0156a93a1815f7d9f7fa01290acf7c3a6ec6 Mon Sep 17 00:00:00 2001 From: Will Gosnold Date: Tue, 27 Oct 2026 19:23:43 +0100 Subject: [PATCH 11/11] test: check hook manager configs against the LEFTHOOK and PRE_COMMIT formats hook install asks the LEFTHOOK and PRE_COMMIT formats whether a config already runs patchbook, only mentions the call, or has a patchbook entry that doesn't always run. The 10 other-name configs, the 48 mention configs and the 7 limited lefthook entries now run against those formats as unit tables. e2e keeps one lefthook and one pre-commit config for the first two, and a skipped lefthook command for the third. The config builders move to helpers.ts so both files share them. LEFTHOOK_PAIRS stays in e2e: the pick of lefthook's config file is private to githook.ts. Co-Authored-By: Claude Opus 5.5 --- test/e2e.test.ts | 107 +++++++++++++-------------------------------- test/helpers.ts | 9 ++++ test/units.test.ts | 67 +++++++++++++++++++++++++++- 3 files changed, 105 insertions(+), 78 deletions(-) diff --git a/test/e2e.test.ts b/test/e2e.test.ts index 4f13d6f8..064aeebe 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -8,7 +8,7 @@ import { dirname, join, relative, resolve } from "node:path"; import type { CheckJson, LastSync, Nearest, SyncReport, UpstreamCheck, UpstreamLock, UpstreamPin } from "../src/api.ts"; import { carriesCrashInjection } from "./crash-build.ts"; import { paste } from "./paste.ts"; -import { CMD, Case, Repo, TIMEOUT, type Run, crashCmd, dedent, fakeClaude, isRoot, permissionTest, sh, splitWords, words } from "./helpers"; +import { CALLS, CMD, Case, Repo, TIMEOUT, type Run, crashCmd, dedent, fakeClaude, isRoot, lefthookCommand, lefthookJob, lefthookJsonCommand, lefthookTomlCommand, permissionTest, PRE_COMMIT_RUNS_ALWAYS, preCommitHook, quoted, sh, splitWords, words } from "./helpers"; const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; @@ -4242,13 +4242,6 @@ for (const [config, existing, dispatcher, parse] of [ } const SOMEONE_ELSES = "echo mine"; -const CALLS = { "pre-commit": "patchbook hook run || exit 1", "post-merge": "patchbook hook build" } as const; -const lefthookCommand = (event: string, name: string, run: string) => `${event}:\n commands:\n ${name}:\n run: ${run}\n`; -const lefthookJob = (event: string, name: string, run: string) => `${event}:\n jobs:\n - name: ${name}\n run: ${run}\n`; -const lefthookJsonCommand = (event: string, name: string, run: string) => `{ "${event}": { "commands": { "${name}": { "run": "${run}" } } } }\n`; -const lefthookTomlCommand = (event: string, name: string, run: string) => `[${event}.commands.${name}]\nrun = "${run}"\n`; -const PRE_COMMIT_RUNS_ALWAYS = " pass_filenames: false\n always_run: true\n"; -const preCommitHook = (id: string, entry: string, extra = PRE_COMMIT_RUNS_ALWAYS, repo = "local") => `repos:\n - repo: ${repo}\n hooks:\n - id: ${id}\n name: ${id}\n entry: ${entry}\n language: system\n${extra}`; const COLLISIONS: [string, string, string, string][] = [ ["a lefthook YAML command", "lefthook.yml", lefthookCommand("pre-commit", "patchbook", SOMEONE_ELSES), "command"], @@ -4294,15 +4287,7 @@ test("hook install checks a post hook for its own call, not for the pre-commit o const OTHER_NAMES: [string, string, string][] = [ ["a lefthook YAML command", "lefthook.yml", lefthookCommand("pre-commit", "record", CALLS["pre-commit"])], - ["a lefthook YAML job", "lefthook.yml", lefthookJob("pre-commit", "record", CALLS["pre-commit"])], - ["a lefthook JSON command", "lefthook.json", lefthookJsonCommand("pre-commit", "record", CALLS["pre-commit"])], - ["a lefthook TOML command", "lefthook.toml", lefthookTomlCommand("pre-commit", "record", CALLS["pre-commit"])], ["a local pre-commit hook", ".pre-commit-config.yaml", preCommitHook("record", "patchbook hook run")], - ["a local pre-commit hook with no stages under default_stages that hold the commit", ".pre-commit-config.yaml", "default_stages: [pre-commit]\n" + preCommitHook("record", "patchbook hook run")], - ["a local pre-commit hook with no stages under default_stages that hold the old commit name", ".pre-commit-config.yaml", "default_stages: [commit, push]\n" + preCommitHook("record", "patchbook hook run")], - ["a local pre-commit hook whose own stages beat default_stages", ".pre-commit-config.yaml", "default_stages: [pre-push]\n" + preCommitHook("record", "patchbook hook run", PRE_COMMIT_RUNS_ALWAYS + " stages: [pre-commit]\n")], - ["a local pre-commit hook with empty args", ".pre-commit-config.yaml", preCommitHook("record", "patchbook hook run", PRE_COMMIT_RUNS_ALWAYS + " args: []\n")], - ["a local pre-commit hook with empty stages that default_stages fill with the commit", ".pre-commit-config.yaml", "default_stages: [pre-commit]\n" + preCommitHook("record", "patchbook hook run", PRE_COMMIT_RUNS_ALWAYS + " stages: []\n")], ]; for (const [name, config, existing] of OTHER_NAMES) { @@ -4319,51 +4304,30 @@ for (const [name, config, existing] of OTHER_NAMES) { }, TIMEOUT); } -/** Text that names the call without running it, or might not run it. */ -const MENTIONS = [ - `echo "patchbook hook run"`, - `printf '%s\\n' 'patchbook hook run'`, - `echo mine # patchbook hook run`, - `echo mine\\n# patchbook hook run`, - `my-patchbook hook run`, - `patchbook hook run-all`, - `if false; then patchbook hook run; fi`, - `./node_modules/.bin/patchbook hook run`, -]; -const quoted = (run: string) => JSON.stringify(run); -const unquoted = (run: string) => JSON.stringify(run).slice(1, -1); -const lefthookJsonJob = (event: string, name: string, run: string) => `{ "${event}": { "jobs": [{ "name": "${name}", "run": "${run}" }] } }\n`; - -const NOT_RUNNING: [string, string, (run: string) => string][] = [ - ["a lefthook YAML command", "lefthook.yml", (run) => lefthookCommand("pre-commit", "diagnostic", quoted(run))], - ["a lefthook YAML job", "lefthook.yml", (run) => lefthookJob("pre-commit", "diagnostic", quoted(run))], - ["a lefthook JSON command", "lefthook.json", (run) => lefthookJsonCommand("pre-commit", "diagnostic", unquoted(run))], - ["a lefthook JSON job", "lefthook.json", (run) => lefthookJsonJob("pre-commit", "diagnostic", unquoted(run))], - ["a lefthook TOML command", "lefthook.toml", (run) => lefthookTomlCommand("pre-commit", "diagnostic", unquoted(run))], - ["a local pre-commit hook", ".pre-commit-config.yaml", (run) => preCommitHook("diagnostic", quoted(run))], +const ECHOED = `echo "patchbook hook run"`; +const NOT_RUNNING: [string, string, string][] = [ + ["a lefthook YAML command", "lefthook.yml", lefthookCommand("pre-commit", "diagnostic", quoted(ECHOED))], + ["a local pre-commit hook", ".pre-commit-config.yaml", preCommitHook("diagnostic", quoted(ECHOED))], ]; -for (const [name, config, build] of NOT_RUNNING) { - for (const run of MENTIONS) { - test(`hook install still adds patchbook's hook when ${name} only mentions the call in ${JSON.stringify(run)}`, () => { - const t = new Case(); - try { - const existing = build(run); - const fork = forkWith(t, { [config]: existing }); - const install = t.pb(["hook", "install"], { cwd: fork.path, timeout: 30_000 }).stderr; - expect(install).toContain("Add this"); - expect(fork.read(config)).toBe(existing); - } finally { - t.cleanup(); - } - }, TIMEOUT); - } +for (const [name, config, existing] of NOT_RUNNING) { + test(`hook install still adds patchbook's hook when ${name} only mentions the call in ${JSON.stringify(ECHOED)}`, () => { + const t = new Case(); + try { + const fork = forkWith(t, { [config]: existing }); + const install = t.pb(["hook", "install"], { cwd: fork.path, timeout: 30_000 }).stderr; + expect(install).toContain("Add this"); + expect(fork.read(config)).toBe(existing); + } finally { + t.cleanup(); + } + }, TIMEOUT); } test("hook install names the clash when a command called patchbook only echoes the call", () => { const t = new Case(); try { - const existing = lefthookCommand("pre-commit", "patchbook", quoted(MENTIONS[0]!)); + const existing = lefthookCommand("pre-commit", "patchbook", quoted(ECHOED)); const fork = forkWith(t, { "lefthook.yml": existing }); const install = t.pb(["hook", "install"], { cwd: fork.path, timeout: 30_000 }).stderr; expect(install).toContain("already has a command named patchbook that doesn't always call `patchbook hook run`"); @@ -4374,29 +4338,18 @@ test("hook install names the clash when a command called patchbook only echoes t }, TIMEOUT); const GENERATED = lefthookCommand("pre-commit", "patchbook", CALLS["pre-commit"]); -const NOT_ALWAYS: [string, string, string][] = [ - ["a skipped lefthook command", "lefthook.yml", GENERATED.replace(" run:", " skip: true\n run:")], - ["a lefthook command limited with only", "lefthook.yml", GENERATED.replace(" run:", " only: [merge]\n run:")], - ["a lefthook command limited with glob", "lefthook.yml", GENERATED.replace(" run:", " glob: '*.md'\n run:")], - ["a lefthook command run from a subfolder", "lefthook.yml", GENERATED.replace(" run:", " root: sub/\n run:")], - ["a skipped lefthook job", "lefthook.yml", lefthookJob("pre-commit", "patchbook", CALLS["pre-commit"]).replace(" run:", " skip: true\n run:")], - ["a skipped lefthook JSON command", "lefthook.json", '{ "pre-commit": { "commands": { "patchbook": { "skip": true, "run": "patchbook hook run || exit 1" } } } }\n'], - ["a lefthook TOML command limited with glob", "lefthook.toml", `[pre-commit.commands.patchbook]\nglob = "*.md"\nrun = "patchbook hook run"\n`], -]; - -for (const [name, config, existing] of NOT_ALWAYS) { - test(`hook install doesn't take ${name} for patchbook's hook`, () => { - const t = new Case(); - try { - const fork = forkWith(t, { [config]: existing }); - const install = t.pb(["hook", "install"], { cwd: fork.path, timeout: 30_000 }).stderr; - expect(install).toContain("that doesn't always call `patchbook hook run`"); - expect(fork.read(config)).toBe(existing); - } finally { - t.cleanup(); - } - }, TIMEOUT); -} +test("hook install doesn't take a skipped lefthook command for patchbook's hook", () => { + const t = new Case(); + try { + const existing = GENERATED.replace(" run:", " skip: true\n run:"); + const fork = forkWith(t, { "lefthook.yml": existing }); + const install = t.pb(["hook", "install"], { cwd: fork.path, timeout: 30_000 }).stderr; + expect(install).toContain("that doesn't always call `patchbook hook run`"); + expect(fork.read("lefthook.yml")).toBe(existing); + } finally { + t.cleanup(); + } +}, TIMEOUT); /** pre-commit splits `entry` into words and runs them without a shell, and appends the file names unless pass_filenames is false. patchbook rejects extra arguments, so these fail every commit or skip it. */ const PRE_COMMIT_NOT_ALWAYS: [string, string][] = [ diff --git a/test/helpers.ts b/test/helpers.ts index f6a08ac6..d3315d18 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -211,3 +211,12 @@ export function permissionTest(name: string, body: (t: C) => voi } }, TIMEOUT); } + +export const CALLS = { "pre-commit": "patchbook hook run || exit 1", "post-merge": "patchbook hook build" } as const; +export const quoted = (run: string) => JSON.stringify(run); +export const lefthookCommand = (event: string, name: string, run: string) => `${event}:\n commands:\n ${name}:\n run: ${run}\n`; +export const lefthookJob = (event: string, name: string, run: string) => `${event}:\n jobs:\n - name: ${name}\n run: ${run}\n`; +export const lefthookJsonCommand = (event: string, name: string, run: string) => `{ "${event}": { "commands": { "${name}": { "run": "${run}" } } } }\n`; +export const lefthookTomlCommand = (event: string, name: string, run: string) => `[${event}.commands.${name}]\nrun = "${run}"\n`; +export const PRE_COMMIT_RUNS_ALWAYS = " pass_filenames: false\n always_run: true\n"; +export const preCommitHook = (id: string, entry: string, extra = PRE_COMMIT_RUNS_ALWAYS, repo = "local") => `repos:\n - repo: ${repo}\n hooks:\n - id: ${id}\n name: ${id}\n entry: ${entry}\n language: system\n${extra}`; diff --git a/test/units.test.ts b/test/units.test.ts index ab4b63ee..cc949cd3 100644 --- a/test/units.test.ts +++ b/test/units.test.ts @@ -1,13 +1,14 @@ import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; +import { dirname, extname, join, resolve } from "node:path"; import type { LastSync, Problem, SyncReport } from "../src/api.ts"; import type { Assembly } from "../src/assemble.ts"; import type { Reserved } from "../src/book.ts"; import type { Edit, Intent } from "../src/changes.ts"; import type { File, Seen } from "../src/lib/fs.ts"; import type { Edited, Snapshot } from "../src/record.ts"; +import { CALLS, lefthookCommand, lefthookJob, lefthookJsonCommand, lefthookTomlCommand, PRE_COMMIT_RUNS_ALWAYS, preCommitHook, quoted } from "./helpers"; const sandbox = mkdtempSync(join(tmpdir(), "units")); const ambientConfigHome = process.env["XDG_CONFIG_HOME"]; @@ -17,6 +18,7 @@ const { applyStructure, describe: describeProblem, parseBuildLock } = await impo const { blockHash, blocksOf, blockSpans, checkEntry, formatEntry, nearest, parsePlaceholders, readEntries, Rules } = await import("../src/blocks.ts"); const { Book, globRe, lockText, parseLock, refuseFoldedUpstream, refuseNestedGit, unsafeVendor } = await import("../src/book.ts"); const { Change, editText, formatChange, parseChange } = await import("../src/changes.ts"); +const { LEFTHOOK, PRE_COMMIT, PRESENT } = await import("../src/hookconfig.ts"); const { changeParts, intentFromEdits, intentFromParagraph, intentSettings, listDiffs, nameFromEdits, pendingParts, PROVIDERS, writeIntents } = await import("../src/intent.ts"); const { Fail } = await import("../src/lib/fail.ts"); const { meantMode, outputMode, recordedModes } = await import("../src/lib/fs.ts"); @@ -2204,3 +2206,66 @@ describe("an edit whose path leaves the tree", () => { expect(refused).toEqual([[edit, expect.stringContaining("must be a path inside the tree: not absolute, with no empty, . or .. segment")]]); }); }); + +describe("a hook manager config's pre-commit entries", () => { + const entry = { event: "pre-commit", run: 'if [ "$PATCHBOOK_HOOK" != 0 ]; then\n patchbook hook run || exit 1\nfi\n' }; + const decide = (file: string, config: string): string => { + const placed = (file === ".pre-commit-config.yaml" ? PRE_COMMIT : LEFTHOOK)[extname(file).slice(1)]!(config, entry, file); + return placed === PRESENT ? "present" : "location" in placed ? "add" : placed.why; + }; + + test.each([ + ["a lefthook YAML command", "lefthook.yml", lefthookCommand("pre-commit", "record", CALLS["pre-commit"])], + ["a lefthook YAML job", "lefthook.yml", lefthookJob("pre-commit", "record", CALLS["pre-commit"])], + ["a lefthook JSON command", "lefthook.json", lefthookJsonCommand("pre-commit", "record", CALLS["pre-commit"])], + ["a lefthook TOML command", "lefthook.toml", lefthookTomlCommand("pre-commit", "record", CALLS["pre-commit"])], + ["a local pre-commit hook", ".pre-commit-config.yaml", preCommitHook("record", "patchbook hook run")], + ["a local pre-commit hook with no stages under default_stages that hold the commit", ".pre-commit-config.yaml", "default_stages: [pre-commit]\n" + preCommitHook("record", "patchbook hook run")], + ["a local pre-commit hook with no stages under default_stages that hold the old commit name", ".pre-commit-config.yaml", "default_stages: [commit, push]\n" + preCommitHook("record", "patchbook hook run")], + ["a local pre-commit hook whose own stages beat default_stages", ".pre-commit-config.yaml", "default_stages: [pre-push]\n" + preCommitHook("record", "patchbook hook run", PRE_COMMIT_RUNS_ALWAYS + " stages: [pre-commit]\n")], + ["a local pre-commit hook with empty args", ".pre-commit-config.yaml", preCommitHook("record", "patchbook hook run", PRE_COMMIT_RUNS_ALWAYS + " args: []\n")], + ["a local pre-commit hook with empty stages that default_stages fill with the commit", ".pre-commit-config.yaml", "default_stages: [pre-commit]\n" + preCommitHook("record", "patchbook hook run", PRE_COMMIT_RUNS_ALWAYS + " stages: []\n")], + ])("%s with another name that runs patchbook counts as patchbook's hook", (_what, file, config) => { + expect(decide(file, config)).toBe("present"); + }); + + const mentions = [ + `echo "patchbook hook run"`, + `printf '%s\\n' 'patchbook hook run'`, + `echo mine # patchbook hook run`, + `echo mine\\n# patchbook hook run`, + `my-patchbook hook run`, + `patchbook hook run-all`, + `if false; then patchbook hook run; fi`, + `./node_modules/.bin/patchbook hook run`, + ]; + const unquoted = (run: string) => quoted(run).slice(1, -1); + const mentioning: [string, string, (run: string) => string][] = [ + ["a lefthook YAML command", "lefthook.yml", (run) => lefthookCommand("pre-commit", "diagnostic", quoted(run))], + ["a lefthook YAML job", "lefthook.yml", (run) => lefthookJob("pre-commit", "diagnostic", quoted(run))], + ["a lefthook JSON command", "lefthook.json", (run) => lefthookJsonCommand("pre-commit", "diagnostic", unquoted(run))], + ["a lefthook JSON job", "lefthook.json", (run) => `{ "pre-commit": { "jobs": [{ "name": "diagnostic", "run": "${unquoted(run)}" }] } }\n`], + ["a lefthook TOML command", "lefthook.toml", (run) => lefthookTomlCommand("pre-commit", "diagnostic", unquoted(run))], + ["a local pre-commit hook", ".pre-commit-config.yaml", (run) => preCommitHook("diagnostic", quoted(run))], + ]; + + test.each(mentioning.flatMap(([what, file, build]) => mentions.map((run) => [what, run, file, build(run)] as const)))( + "%s that only mentions the call in %p still gets patchbook's lines", + (_what, _run, file, config) => { + expect(decide(file, config)).toBe("add"); + }, + ); + + const generated = lefthookCommand("pre-commit", "patchbook", CALLS["pre-commit"]); + test.each([ + ["a skipped lefthook command", "command", "lefthook.yml", generated.replace(" run:", " skip: true\n run:")], + ["a lefthook command limited with only", "command", "lefthook.yml", generated.replace(" run:", " only: [merge]\n run:")], + ["a lefthook command limited with glob", "command", "lefthook.yml", generated.replace(" run:", " glob: '*.md'\n run:")], + ["a lefthook command run from a subfolder", "command", "lefthook.yml", generated.replace(" run:", " root: sub/\n run:")], + ["a skipped lefthook job", "job", "lefthook.yml", lefthookJob("pre-commit", "patchbook", CALLS["pre-commit"]).replace(" run:", " skip: true\n run:")], + ["a skipped lefthook JSON command", "command", "lefthook.json", '{ "pre-commit": { "commands": { "patchbook": { "skip": true, "run": "patchbook hook run || exit 1" } } } }\n'], + ["a lefthook TOML command limited with glob", "command", "lefthook.toml", `[pre-commit.commands.patchbook]\nglob = "*.md"\nrun = "patchbook hook run"\n`], + ])("%s is not taken for patchbook's hook", (_what, kind, file, config) => { + expect(decide(file, config)).toBe(`its pre-commit already has a ${kind} named patchbook that doesn't always call \`patchbook hook run\``); + }); +});