diff --git a/tests/boundary/cli/referenceSourceExclusions.test.ts b/tests/boundary/cli/referenceSourceExclusions.test.ts index 77495d25d4..cfb421e28e 100644 --- a/tests/boundary/cli/referenceSourceExclusions.test.ts +++ b/tests/boundary/cli/referenceSourceExclusions.test.ts @@ -90,62 +90,6 @@ describe.skipIf(process.platform === "win32")( expect(await readlink(join(root, "alias"))).toBe("dist"); }, ); - - cliTest( - "reports project, default, and explicit secret exclusions", - async ({ cli }) => { - const root = await createTestTempDirectory("rea-reference-exclusions-"); - const logs = join(root, "logs"); - await mkdir(logs); - await Promise.all([ - writeFile(join(root, ".gitignore"), "project.tmp\n"), - writeFile(join(root, "project.tmp"), "project policy\n"), - writeFile(join(logs, "application.log"), "default policy\n"), - writeFile(join(root, "private.txt"), "sensitive local file\n"), - writeFile(join(root, "source.ts"), "export const value = 1;\n"), - ]); - - const result = await cli.run({ - arguments: ["import-reference-source", root, "--json"], - cwd: root, - environment: { - HOME: root, - USERPROFILE: root, - XDG_CONFIG_HOME: root, - XDG_CACHE_HOME: root, - REA_REFERENCE_SECRET_PATTERNS_JSON: '["private.txt"]', - }, - }); - - expect(result.exitCode).toBe(0); - const graph = historicalSourceGraphSchema.parse(result.json); - expect(graph.exclusions).toEqual( - expect.arrayContaining([ - { - path: "project.tmp", - entry_kind: "file", - reason: "project-ignored", - pattern: "project.tmp", - }, - { - path: "logs/application.log", - entry_kind: "file", - reason: "default-ignored", - pattern: "*.log", - }, - { - path: "private.txt", - entry_kind: "file", - reason: "configured-secret", - pattern: "private.txt", - }, - ]), - ); - expect(graph.entries).toContainEqual( - expect.objectContaining({ path: "source.ts", kind: "file" }), - ); - }, - ); }, ); @@ -186,9 +130,32 @@ describe.skipIf(process.platform === "win32")( expect(emptyGraph.entries.map((entry) => entry.path)).toEqual( omittedGraph.entries.map((entry) => entry.path), ); - expect(omittedGraph.exclusions).not.toContainEqual( - expect.objectContaining({ reason: "caller-excluded" }), - ); + expect(omittedGraph.exclusions).toEqual([ + { + path: "keep.log", + entry_kind: "file", + reason: "default-ignored", + pattern: "*.log", + }, + { + path: "logs/application.log", + entry_kind: "file", + reason: "default-ignored", + pattern: "*.log", + }, + { + path: "private.txt", + entry_kind: "file", + reason: "configured-secret", + pattern: "private.txt", + }, + { + path: "project.tmp", + entry_kind: "file", + reason: "project-ignored", + pattern: "project.tmp", + }, + ]); expect(omittedGraph.entries).toContainEqual( expect.objectContaining({ path: "notes.tmp", kind: "file" }), ); @@ -198,12 +165,6 @@ describe.skipIf(process.platform === "win32")( kind: "file", }), ); - expect(omittedGraph.exclusions).toContainEqual({ - path: "keep.log", - entry_kind: "file", - reason: "default-ignored", - pattern: "*.log", - }); expect(selected.exitCode).toBe(0); const selectedGraph = historicalSourceGraphSchema.parse(selected.json); diff --git a/tests/boundary/filesystem/referenceSourceGitMetadataExclusion.test.ts b/tests/boundary/filesystem/referenceSourceGitMetadataExclusion.test.ts index 1f072bd554..1a1d493d8d 100644 --- a/tests/boundary/filesystem/referenceSourceGitMetadataExclusion.test.ts +++ b/tests/boundary/filesystem/referenceSourceGitMetadataExclusion.test.ts @@ -1,12 +1,12 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import ignore from "ignore"; import { describe, expect, it } from "vitest"; -import { DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS } from "../../../src/application/ReferenceSourceImportTypes.js"; +import { prepareReferenceSourceImport } from "../../../src/application/ReferenceSourceImportPolicy.js"; import { createHistoricalSourceManifest } from "../../../src/domain/referenceSourceGraph.js"; -import { execFileOutput } from "../../../src/process/ExecFileOutput.js"; +import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { importReferenceSource } from "../../support/referenceSourceResourceScope.js"; +import { createReferenceSourceGitFixture } from "../../support/referenceSourceGitFixture.js"; const importTree = async ( root: string, @@ -23,38 +23,28 @@ const importTree = async ( return result.value; }; -const fixtureGit = ( - directory: string, - configuration: string, - args: readonly string[], -) => - execFileOutput( - "git", - ["-c", `core.hooksPath=${join(configuration, "no-hooks")}`, ...args], - { - cwd: directory, - env: { - ...Object.fromEntries( - Object.entries(process.env).filter( - ([name]) => !name.toUpperCase().startsWith("GIT_"), - ), - ), - GIT_CONFIG_GLOBAL: join(configuration, "gitconfig"), - GIT_CONFIG_NOSYSTEM: "1", - GIT_TEMPLATE_DIR: join(configuration, "no-template"), - }, - }, +it("prepares Git metadata exclusions and keeps directory-only defaults distinct", async () => { + const root = await createTestTempDirectory("rea-reference-git-policy-"); + const prepared = await withArtifactResourceScope((resources) => + prepareReferenceSourceImport( + { root, caller: "git-metadata-test", policy: { secretPatterns: [] } }, + resources, + ), ); - -it("excludes Git metadata files and directories without broadening directory-only defaults", () => { - const matcher = ignore().add([...DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS]); - for (const path of [".git", ".git/", "nested/.git", "nested/.git/"]) - expect(matcher.ignores(path), path).toBe(true); + if (!prepared.ok) throw prepared.error; + const { ignored } = prepared.value; + for (const prefix of ["", "nested/"]) + for (const pattern of [".git", ".git/"]) + expect(ignored.test(prefix + pattern)).toMatchObject({ + ignored: true, + rule: { pattern, mark: "default-ignored" }, + }); for (const path of [".gitignore", ".github", ".gitkeep", "dist"]) - expect(matcher.ignores(path), path).toBe(false); - expect(matcher.ignores("dist/")).toBe(true); - expect(matcher.test(".git").rule?.pattern).toBe(".git"); - expect(matcher.test(".git/").rule?.pattern).toBe(".git/"); + expect(ignored.test(path).ignored, path).toBe(false); + expect(ignored.test("dist/")).toMatchObject({ + ignored: true, + rule: { pattern: "dist/", mark: "default-ignored" }, + }); }); describe.skipIf(process.platform === "win32")( @@ -63,18 +53,14 @@ describe.skipIf(process.platform === "win32")( it("keeps linked-worktree identities stable while retaining HEAD and ordinary-checkout provenance", async () => { const root = await createTestTempDirectory("rea-reference-git-metadata-"); const repository = join(root, "repository"); - await Promise.all([ - mkdir(join(root, "no-hooks")), - mkdir(join(root, "no-template")), - writeFile(join(root, "gitconfig"), ""), - ]); + const fixtureGit = await createReferenceSourceGitFixture(root); await mkdir(join(repository, "src"), { recursive: true }); await writeFile( join(repository, "src", "main.js"), "export const value = 7;\n", ); await writeFile(join(repository, ".gitignore"), "*.log\n"); - const git = (...args: string[]) => fixtureGit(repository, root, args); + const git = (...args: string[]) => fixtureGit(repository, ...args); await git("init", "--initial-branch=main"); await git("add", ".gitignore", "src/main.js"); await git( @@ -94,7 +80,7 @@ describe.skipIf(process.platform === "win32")( for (const worktree of [leftRoot, rightRoot]) { await git("worktree", "add", "--detach", worktree, head); expect( - (await fixtureGit(worktree, root, ["status", "--porcelain"])).stdout, + (await fixtureGit(worktree, "status", "--porcelain")).stdout, ).toBe(""); } expect(await readFile(join(leftRoot, ".git"), "utf8")).not.toBe( @@ -117,13 +103,9 @@ describe.skipIf(process.platform === "win32")( }; const left = await importSelectedTree(leftRoot); const right = await importSelectedTree(rightRoot); - const repeated = await importSelectedTree(leftRoot); expect(createHistoricalSourceManifest(left)).toEqual( createHistoricalSourceManifest(right), ); - expect(createHistoricalSourceManifest(repeated)).toEqual( - createHistoricalSourceManifest(left), - ); for (const graph of [left, right]) expect(graph.exclusions).toEqual([ { @@ -144,65 +126,53 @@ describe.skipIf(process.platform === "win32")( ]); }); - it.each(["file", "directory"] as const)( - "prunes nested .git %s metadata and preserves configured-secret precedence", - async (kind) => { - const root = await createTestTempDirectory("rea-reference-nested-git-"); - const nested = join(root, "nested"); - await mkdir(nested); - if (kind === "file") - await writeFile( - join(nested, ".git"), - "gitdir: /checkout-specific/metadata\n", - ); - else { - await mkdir(join(nested, ".git", "hooks"), { recursive: true }); - await writeFile( - join(nested, ".git", "hooks", "pre-commit"), - "metadata\n", - ); - } - for (const name of [ - ".gitignore", - ".github", - ".gitkeep", - "dist", - "source.js", - ]) - await writeFile(join(nested, name), ""); - for (const secretPatterns of [[], [".git"]]) { - const graph = await importTree( - root, - secretPatterns, - secretPatterns.length === 0 ? [] : ["!.git"], - ); - expect(graph.exclusions).toEqual([ - { - path: "nested/.git", - entry_kind: kind, - reason: - secretPatterns.length === 0 - ? "default-ignored" - : "configured-secret", - pattern: - secretPatterns.length === 0 && kind === "directory" - ? ".git/" - : ".git", - }, - ]); - expect( - graph.entries - .filter(({ kind }) => kind === "file") - .map(({ path }) => path), - ).toEqual([ - "nested/.github", - "nested/.gitignore", - "nested/.gitkeep", - "nested/dist", - "nested/source.js", - ]); - } - }, - ); + it("prunes both nested Git metadata kinds and preserves configured-secret precedence", async () => { + const root = await createTestTempDirectory("rea-reference-nested-git-"); + await Promise.all([ + mkdir(join(root, "pointer")), + mkdir(join(root, "repository", ".git", "hooks"), { recursive: true }), + ]); + await Promise.all([ + writeFile(join(root, "pointer", ".git"), "gitdir: ../metadata\n"), + writeFile( + join(root, "repository", ".git", "hooks", "pre-commit"), + "metadata\n", + ), + ...[".gitignore", ".github", ".gitkeep", "dist", "source.js"].map( + (name) => writeFile(join(root, "pointer", name), ""), + ), + ]); + + for (const mode of ["default", "secret"] as const) { + const secret = mode === "secret"; + const graph = await importTree( + root, + secret ? [".git"] : [], + secret ? ["!.git"] : [], + ); + const reason = secret ? "configured-secret" : "default-ignored"; + expect(graph.exclusions, mode).toEqual([ + { path: "pointer/.git", entry_kind: "file", reason, pattern: ".git" }, + { + path: "repository/.git", + entry_kind: "directory", + reason, + pattern: secret ? ".git" : ".git/", + }, + ]); + expect( + graph.entries.map(({ path }) => path), + mode, + ).toEqual([ + "pointer", + "pointer/.github", + "pointer/.gitignore", + "pointer/.gitkeep", + "pointer/dist", + "pointer/source.js", + "repository", + ]); + } + }); }, ); diff --git a/tests/boundary/filesystem/referenceSourceIgnorePolicy.test.ts b/tests/boundary/filesystem/referenceSourceIgnorePolicy.test.ts index 86b11eead4..6b0df1711a 100644 --- a/tests/boundary/filesystem/referenceSourceIgnorePolicy.test.ts +++ b/tests/boundary/filesystem/referenceSourceIgnorePolicy.test.ts @@ -2,7 +2,7 @@ import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { execFileOutput } from "../../../src/process/ExecFileOutput.js"; +import { createReferenceSourceGitFixture } from "../../support/referenceSourceGitFixture.js"; import { importReferenceSource } from "../../support/referenceSourceResourceScope.js"; const importTree = async (root: string) => { @@ -54,6 +54,7 @@ it("keeps unreadable scoped policy fatal after opening a readable directory", as const child = join(root, "child"); await mkdir(join(child, ".gitignore"), { recursive: true }); await writeFile(join(child, "unexamined.ts"), "export const value = 1;\n"); + await writeFile(join(root, "observed.ts"), "export const observed = true;\n"); const result = await importReferenceSource({ root, caller: "scoped-policy-refusal-test", @@ -62,25 +63,26 @@ it("keeps unreadable scoped policy fatal after opening a readable directory", as if (result.ok) throw new Error("Invalid scoped policy was ignored"); expect(result.error.code).toBe("io"); expect(result.error.message).toContain(join(child, ".gitignore")); - expect(result.error.partial?.entries).not.toContainEqual( + const entries = result.error.partial?.entries; + expect(entries).toContainEqual( + expect.objectContaining({ path: "observed.ts", status: "read" }), + ); + expect(entries).not.toContainEqual( expect.objectContaining({ path: "child/unexamined.ts" }), ); }); -it("scopes nested ignore rules and negations like Git while preserving mandatory exclusions", async () => { - const root = await createTestTempDirectory("rea-reference-scoped-policy-"); - await execFileOutput("git", ["init", "--initial-branch=main", root]); - await execFileOutput("git", [ - "-C", - root, - "config", - "core.ignorecase", - "false", - ]); +it("scopes nested ignore rules and honors local Git case policy", async () => { + const fixture = await createTestTempDirectory("rea-reference-scoped-policy-"); + const git = await createReferenceSourceGitFixture(fixture); + const root = join(fixture, "source"); + await mkdir(root); + await git(root, "init", "--initial-branch=main"); + await git(root, "config", "core.ignorecase", "false"); await mkdir(join(root, "packages", "widget", "blocked"), { recursive: true }); await mkdir(join(root, "packages", "widget", "node_modules")); await mkdir(join(root, "sibling")); - await writeFile(join(root, ".gitignore"), "*.tmp\nblocked/\n"); + await writeFile(join(root, ".gitignore"), "*.tmp\n*.CASE\nblocked/\n"); await writeFile( join(root, "packages", "widget", ".gitignore"), "/local.js\n!keep.tmp\n!node_modules/\n", @@ -91,10 +93,12 @@ it("scopes nested ignore rules and negations like Git while preserving mandatory ); const excluded = [ "drop.tmp", + "upper.CASE", "packages/widget/local.js", "packages/widget/blocked/inside.js", ]; const included = [ + "lower.case", "packages/widget/keep.tmp", "packages/widget/main.js", "sibling/local.js", @@ -105,14 +109,13 @@ it("scopes nested ignore rules and negations like Git while preserving mandatory "packages/widget/node_modules/dependency.js", ]) await writeFile(join(root, path), "export const value = 1;\n"); - const oracle = await execFileOutput("git", [ - "-C", + const oracle = await git( root, "check-ignore", "--no-index", ...excluded, ...included, - ]); + ); expect(oracle.stdout.trim().split(/\r?\n/u)).toEqual(excluded); const graph = await importTree(root); const files = graph.entries @@ -139,44 +142,21 @@ it("scopes nested ignore rules and negations like Git while preserving mandatory expect( await readFile(join(root, "packages", "widget", "keep.tmp"), "utf8"), ).toBe("export const value = 1;\n"); + await git(root, "config", "core.ignorecase", "true"); + const folded = await git(root, "check-ignore", "--no-index", "lower.case"); + expect(folded.stdout.trim()).toBe("lower.case"); + const foldedGraph = await importTree(root); + expect(foldedGraph.exclusions).toContainEqual({ + path: "lower.case", + entry_kind: "file", + reason: "project-ignored", + pattern: "*.CASE", + }); + expect(foldedGraph.entries.some(({ path }) => path === "lower.case")).toBe( + false, + ); }); -it.each([false, true])( - "honors local core.ignorecase=%s against Git's check-ignore oracle", - async (ignoreCase) => { - const root = await createTestTempDirectory("rea-reference-ignore-case-"); - await execFileOutput("git", ["init", "--initial-branch=main", root]); - await execFileOutput("git", [ - "-C", - root, - "config", - "core.ignorecase", - String(ignoreCase), - ]); - await writeFile(join(root, ".gitignore"), "*.TMP\n"); - await writeFile(join(root, "upper.TMP"), "upper\n"); - await writeFile(join(root, "lower.tmp"), "lower\n"); - const oracle = await execFileOutput("git", [ - "-C", - root, - "check-ignore", - "--no-index", - "upper.TMP", - "lower.tmp", - ]); - const expected = oracle.stdout.trim().split(/\r?\n/u); - const graph = await importTree(root); - expect( - graph.exclusions - .filter(({ reason }) => reason === "project-ignored") - .map(({ path }) => path), - ).toEqual([...expected].sort()); - expect(graph.entries.some(({ path }) => path === "lower.tmp")).toBe( - !ignoreCase, - ); - }, -); - it.skipIf(process.platform === "win32")( "binds Git pointer/configuration reads to physical symlink-parent selection", async () => { diff --git a/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts b/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts index 0420b3509b..cb6c463d17 100644 --- a/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts +++ b/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts @@ -16,7 +16,6 @@ import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vitest"; import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js"; import { readReferenceSourceVcs } from "../../../src/application/ReferenceSourceVcsAdapter.js"; -import { execFileOutput } from "../../../src/process/ExecFileOutput.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; vi.mock("node:fs/promises", async (importOriginal) => { @@ -83,41 +82,6 @@ const failCloseUntilAllowed = ( }; }; -const createPackedRefRepository = async () => { - const root = await createTestTempDirectory("rea-reference-packed-owner-"); - await execFileOutput("git", ["init", "--initial-branch=main"], { cwd: root }); - await writeFile(join(root, "main.ts"), "export const value = 1;\n"); - await execFileOutput( - "git", - [ - "-c", - "user.name=REA fixture", - "-c", - "user.email=fixture@example.invalid", - "-c", - "commit.gpgsign=false", - "commit", - "--allow-empty", - "-m", - "fixture", - ], - { cwd: root }, - ); - const head = ( - await execFileOutput("git", ["rev-parse", "HEAD"], { cwd: root }) - ).stdout.trim(); - await execFileOutput("git", ["pack-refs", "--all", "--prune"], { - cwd: root, - }); - const looseRef = join(root, ".git", "refs", "heads", "main"); - const packedRefs = join(root, ".git", "packed-refs"); - await actual.mkdir(join(root, ".git", "refs", "heads"), { - recursive: true, - }); - await writeFile(looseRef, `${head}\n`); - return { root, looseRef, packedRefs }; -}; - it.each([".", "nested"])( "retains failed %s/.gitignore cleanup under the caller's scope", async (directory) => { @@ -160,8 +124,9 @@ it.each([".", "nested"])( it("retains local Git configuration cleanup before trusting ignore policy", async () => { const root = await createTestTempDirectory("rea-reference-config-owner-"); - await execFileOutput("git", ["init", "--initial-branch=main"], { cwd: root }); + await mkdir(join(root, ".git")); const path = join(root, ".git", "config"); + await writeFile(path, "[core]\nignorecase = true\n"); const resources = new ArtifactResourceScope(); const close = failCloseUntilAllowed(path); onTestFinished(async () => { @@ -190,15 +155,16 @@ it("preserves Git metadata cleanup failure and the completed source read", async const root = await createTestTempDirectory("rea-reference-head-owner-"); const repository = join(root, "repository"); const sourceRoot = join(root, "source"); - await Promise.all([mkdir(repository), mkdir(sourceRoot)]); - await execFileOutput("git", ["init", "--initial-branch=main"], { - cwd: repository, - }); + await Promise.all([ + mkdir(join(repository, ".git"), { recursive: true }), + mkdir(sourceRoot), + ]); const source = join(sourceRoot, "main.ts"); const bytes = "export const value = 1;\n"; await writeFile(source, bytes); await writeFile(join(sourceRoot, ".git"), "gitdir: ../repository/.git\n"); const head = join(repository, ".git", "HEAD"); + await writeFile(head, "ref: refs/heads/main\n"); const resources = new ArtifactResourceScope(); const close = failCloseUntilAllowed(head); onTestFinished(async () => { @@ -241,111 +207,81 @@ it("preserves Git metadata cleanup failure and the completed source read", async expect(close.calls()).toBe(3); }); -it("retains later packed-ref cleanup after an earlier loose-ref read failure", async () => { - const { root, looseRef, packedRefs } = await createPackedRefRepository(); +it.each([ + { read: "loose", close: "packed" }, + { read: "packed", close: "loose" }, +] as const)( + "observes the $read ref read failure and retains $close ref cleanup", + async ({ read, close }) => { + const root = await createTestTempDirectory("rea-reference-packed-owner-"); + const gitdir = join(root, ".git"); + const loose = join(gitdir, "refs", "heads", "main"); + const packed = join(gitdir, "packed-refs"); + const head = "0123456789abcdef0123456789abcdef01234567"; + await mkdir(join(gitdir, "refs", "heads"), { recursive: true }); + await Promise.all([ + writeFile(join(gitdir, "HEAD"), "ref: refs/heads/main\n"), + writeFile(loose, `${head}\n`), + writeFile(packed, `${head} refs/heads/main\n`), + ]); - const resources = new ArtifactResourceScope(); - let allowClose = false; - let looseReadFailed = false; - const packedCloseCalls = new Map(); - openMock.mockImplementation(async (...args) => { - const handle = await actual.open(...args); - const path = resolve(String(args[0])); - if (path === resolve(looseRef)) { - vi.spyOn(handle, "read").mockImplementation(async () => { - looseReadFailed = true; - throw Object.assign(new Error("injected loose ref EIO"), { - code: "EIO", + const paths = { loose, packed }; + const readFailure = Object.assign(new Error(`injected ${read} ref EIO`), { + code: "EIO", + }); + const closeFailure = new Error(`injected ${close} ref close failure`); + const closeCalls = new Map(); + let readAttempted = false; + let allowClose = false; + const resources = new ArtifactResourceScope(); + openMock.mockImplementation(async (...args) => { + const handle = await actual.open(...args); + const path = resolve(String(args[0])); + if (path === paths[read]) + vi.spyOn(handle, "read").mockImplementation(async () => { + readAttempted = true; + throw readFailure; }); - }); - } - if (path === resolve(packedRefs)) { - const close = handle.close.bind(handle); - vi.spyOn(handle, "close").mockImplementation(async () => { - packedCloseCalls.set(handle, (packedCloseCalls.get(handle) ?? 0) + 1); - if (!allowClose) throw new Error("injected packed-refs close failure"); - await close(); - }); - } - return handle; - }); - onTestFinished(async () => { - allowClose = true; - await resources.close().catch(() => undefined); - }); - - const result = await readReferenceSourceVcs(root, resources); - expect(looseReadFailed).toBe(true); - expect(result).toMatchObject({ - ok: false, - error: { - code: "io", - cleanup: { - resources: [packedRefs], - reason: expect.stringContaining("injected packed-refs close failure"), - }, - }, - }); - expect([...packedCloseCalls.values()]).toEqual( - Array.from({ length: packedCloseCalls.size }, () => 2), - ); - - allowClose = true; - await resources.close(); - expect([...packedCloseCalls.values()]).toEqual( - Array.from({ length: packedCloseCalls.size }, () => 3), - ); -}); - -it("keeps a later packed-ref read error primary over earlier loose-ref cleanup", async () => { - const { root, looseRef, packedRefs } = await createPackedRefRepository(); - const resources = new ArtifactResourceScope(); - let allowClose = false; - const looseCloseCalls = new Map(); - openMock.mockImplementation(async (...args) => { - const handle = await actual.open(...args); - const path = resolve(String(args[0])); - if (path === resolve(looseRef)) { - const close = handle.close.bind(handle); - vi.spyOn(handle, "close").mockImplementation(async () => { - looseCloseCalls.set(handle, (looseCloseCalls.get(handle) ?? 0) + 1); - if (!allowClose) throw new Error("injected loose ref close failure"); - await close(); - }); - } - if (path === resolve(packedRefs)) - vi.spyOn(handle, "read").mockImplementation(async () => { - throw Object.assign(new Error("injected packed-refs EIO"), { - code: "EIO", + if (path === paths[close]) { + const closeHandle = handle.close.bind(handle); + vi.spyOn(handle, "close").mockImplementation(async () => { + closeCalls.set(handle, (closeCalls.get(handle) ?? 0) + 1); + if (!allowClose) throw closeFailure; + await closeHandle(); }); + } + return handle; + }); + try { + const result = await readReferenceSourceVcs(root, resources); + if (result.ok) throw new Error("Expected Git metadata read failure"); + expect(result.error).toMatchObject({ + code: "io", + cleanup: { + resources: [paths[close]], + reason: expect.stringContaining(closeFailure.message), + }, }); - return handle; - }); - onTestFinished(async () => { - allowClose = true; - await resources.close().catch(() => undefined); - }); - - const result = await readReferenceSourceVcs(root, resources); - if (result.ok) throw new Error("Expected Git metadata read to fail"); - expect(result.error.message).toContain("injected packed-refs EIO"); - expect(result.error.message).not.toContain( - "injected loose ref close failure", - ); - expect(result.error.cleanup).toMatchObject({ - resources: [looseRef], - reason: expect.stringContaining("injected loose ref close failure"), - }); - expect([...looseCloseCalls.values()]).toEqual( - Array.from({ length: looseCloseCalls.size }, () => 2), - ); - - allowClose = true; - await resources.close(); - expect([...looseCloseCalls.values()]).toEqual( - Array.from({ length: looseCloseCalls.size }, () => 3), - ); -}); + expect(readAttempted).toBe(true); + if (read === "packed") { + const failure = result.error.cause; + if ( + !(failure instanceof Error && failure.cause instanceof AggregateError) + ) + throw new Error("Expected the Git metadata failure aggregate"); + expect(failure.cause.cause).toBe(readFailure); + expect(result.error.message).toContain(readFailure.message); + } + expect(new Set(closeCalls.values())).toEqual(new Set([2])); + expect(resources.cleanupResources).toEqual([paths[close]]); + } finally { + allowClose = true; + await resources.close(); + } + expect(new Set(closeCalls.values())).toEqual(new Set([3])); + expect(resources.hasPending).toBe(false); + }, +); it.each([ ["stat", false], diff --git a/tests/boundary/filesystem/referenceSourceVcs.test.ts b/tests/boundary/filesystem/referenceSourceVcs.test.ts index 3e46be0ce1..a0004ceeaa 100644 --- a/tests/boundary/filesystem/referenceSourceVcs.test.ts +++ b/tests/boundary/filesystem/referenceSourceVcs.test.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { expect, it } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js"; -import { execFileOutput } from "../../../src/process/ExecFileOutput.js"; +import { createReferenceSourceGitFixture } from "../../support/referenceSourceGitFixture.js"; import { readReferenceSourceVcs } from "../../../src/application/ReferenceSourceVcsAdapter.js"; const readVcs = (root: string, signal?: AbortSignal) => @@ -17,11 +17,11 @@ it("reads a linked worktree's own branch and detached HEAD through shared Git re const root = await createTestTempDirectory("rea-reference-worktree-"); const repository = join(root, "repository"); await mkdir(repository); - const git = (...args: string[]) => - execFileOutput("git", args, { cwd: repository }); - await git("init", "--initial-branch=main"); - const commit = () => + const git = await createReferenceSourceGitFixture(root); + await git(repository, "init", "--initial-branch=main"); + const commit = (directory: string, title: string) => git( + directory, "-c", "user.name=REA fixture", "-c", @@ -31,31 +31,14 @@ it("reads a linked worktree's own branch and detached HEAD through shared Git re "commit", "--allow-empty", "-m", - "fixture", + title, ); - await commit(); - const mainHead = (await git("rev-parse", "HEAD")).stdout.trim(); + await commit(repository, "fixture"); + const mainHead = (await git(repository, "rev-parse", "HEAD")).stdout.trim(); const linked = join(root, "linked"); - await git("worktree", "add", "-b", "linked", linked); - await execFileOutput( - "git", - [ - "-c", - "user.name=REA fixture", - "-c", - "user.email=fixture@example.invalid", - "-c", - "commit.gpgsign=false", - "commit", - "--allow-empty", - "-m", - "linked fixture", - ], - { cwd: linked }, - ); - const linkedHead = ( - await execFileOutput("git", ["rev-parse", "HEAD"], { cwd: linked }) - ).stdout.trim(); + await git(repository, "worktree", "add", "-b", "linked", linked); + await commit(linked, "linked fixture"); + const linkedHead = (await git(linked, "rev-parse", "HEAD")).stdout.trim(); expect(linkedHead).not.toBe(mainHead); expect(await readVcs(repository)).toEqual({ kind: "git", @@ -67,15 +50,13 @@ it("reads a linked worktree's own branch and detached HEAD through shared Git re head: linkedHead, dirty: null, }); - await git("pack-refs", "--all", "--prune"); + await git(repository, "pack-refs", "--all", "--prune"); expect(await readVcs(linked)).toEqual({ kind: "git", head: linkedHead, dirty: null, }); - await execFileOutput("git", ["checkout", "--detach", mainHead], { - cwd: linked, - }); + await git(linked, "checkout", "--detach", mainHead); expect(await readVcs(linked)).toEqual({ kind: "git", head: mainHead, diff --git a/tests/support/referenceSourceGitFixture.ts b/tests/support/referenceSourceGitFixture.ts new file mode 100644 index 0000000000..317b2eb5e5 --- /dev/null +++ b/tests/support/referenceSourceGitFixture.ts @@ -0,0 +1,28 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { execFileOutput } from "../../src/process/ExecFileOutput.js"; + +/** Run Git's fixture and oracle commands without host configuration or hooks. */ +export const createReferenceSourceGitFixture = async ( + configuration: string, +) => { + const hooks = join(configuration, "no-hooks"); + const template = join(configuration, "no-template"); + const config = join(configuration, "gitconfig"); + await Promise.all([mkdir(hooks), mkdir(template), writeFile(config, "")]); + const environment = { + ...Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => !name.toUpperCase().startsWith("GIT_"), + ), + ), + GIT_CONFIG_GLOBAL: config, + GIT_CONFIG_NOSYSTEM: "1", + GIT_TEMPLATE_DIR: template, + }; + return (cwd: string, ...args: readonly string[]) => + execFileOutput("git", ["-c", `core.hooksPath=${hooks}`, ...args], { + cwd, + env: environment, + }); +};