import { assert, describe, it } from "@effect/vitest"; import { MemoryFileSystem } from "@effected/memfs"; import type { FileSystem } from "effect"; import { ConfigProvider, Effect, Layer, Path, Sink, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import type { GitShape } from "../src/Git.js"; import { AheadBehind, Git, GitCommandError, NotARepositoryError, SparseCheckoutSetResult, SparseCheckoutState, UnknownRefError, } from "../src/Git.js"; import type { ScriptResult } from "./fixtures.js"; import { GitOverMemory, scripted } from "./fixtures.js"; // The members okfit's `bundles mount` builds on: clone, aheadBehind, the // info/exclude pair, sparseCheckoutList, sparseCheckoutSet's result, the // submoduleAdd options and the access-refusal reading of a network failure. // Real-git counterparts live in integration/GitMount.int.test.ts. const cwd = "/repo"; /** Whether an argv is the ssh-command probe a network member runs first. */ const isSshProbe = (args: ReadonlyArray): boolean => args.length === 3 && args[0] === "config" && args[1] === "--get" && (args[2] === "core.sshCommand" || args[2] === "ssh.variant"); /** * Runs `program` against `Git.layer` over a scripted spawner, the ssh probes answered "unset". `volume` is the * `FileSystem` the layer is BUILT with (an empty memfs by default): `Git.layer` resolves it at construction, so a * seeded volume reaches the file-reading members only through here, never through a provide around the call. */ const run = ( program: Effect.Effect, byArgs: (args: ReadonlyArray) => ScriptResult, volume: Layer.Layer = MemoryFileSystem.layer, ) => program.pipe( Effect.provide(Git.layer.pipe(Layer.provide(Layer.mergeAll(volume, Path.layer)))), Effect.provide(scripted((args) => (isSshProbe(args) ? { exit: 1 } : byArgs(args)))), Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord({}))), ); const call = (f: (git: GitShape) => Effect.Effect) => Effect.flatMap(Git, f); const neverSpawn = (): ScriptResult => { throw new Error("spawned — a pre-spawn guard did not fire"); }; describe("clone", () => { it.effect("runs the clone argv and succeeds", () => Effect.gen(function* () { const seen: Array> = []; yield* run( call((git) => git.clone(cwd, { url: "file:///srv/r.git", directory: "r", depth: 1, sparse: true })), (args) => { seen.push(args); return {}; }, ); assert.deepStrictEqual(seen, [["clone", "--depth", "1", "--sparse", "--", "file:///srv/r.git", "r"]]); }), ); it.effect("a branch the remote lacks is an UnknownRefError naming the branch", () => Effect.gen(function* () { const error = yield* Effect.flip( run( call((git) => git.clone(cwd, { url: "/srv/r.git", directory: "r", branch: "nob" })), () => ({ exit: 128, stderr: "Cloning into 'r'...\nfatal: Remote branch nob not found in upstream origin\n", }), ), ); assert.instanceOf(error, UnknownRefError); assert.strictEqual(error.ref, "nob"); }), ); it.effect("refuses a non-positive depth and an option-like branch before spawning", () => Effect.gen(function* () { for (const options of [{ depth: 0 }, { depth: 1.5 }, { branch: "--upload-pack=evil" }]) { const error = yield* Effect.flip( run( call((git) => git.clone(cwd, { url: "/srv/r.git", directory: "r", ...options })), neverSpawn, ), ); assert.instanceOf(error, GitCommandError); assert.strictEqual(error.kind, "refused"); } }), ); it.effect("a not-a-repository phrase is not a NotARepositoryError: clone needs no repository at cwd", () => Effect.gen(function* () { const error = yield* Effect.flip( run( call((git) => git.clone(cwd, { url: "/srv/r.git", directory: "r" })), () => ({ exit: 128, stderr: "fatal: not a git repository (or any of the parent directories): .git\n", }), ), ); assert.instanceOf(error, GitCommandError); }), ); it.effect("keeps a credential out of the error's args and stderr", () => Effect.gen(function* () { const error = yield* Effect.flip( run( call((git) => git.clone(cwd, { url: "https://u:ghp_secret@example.com/r.git", directory: "r" })), () => ({ exit: 128, stderr: "fatal: unable to access 'https://u:ghp_secret@example.com/r.git/': Could not resolve host: example.com\n", }), ), ); assert.instanceOf(error, GitCommandError); assert.notInclude(error.args.join(" "), "ghp_secret"); assert.notInclude(error.stderr, "ghp_secret"); assert.strictEqual(error.access, "unreachable"); }), ); }); describe("access refusal", () => { // Each row's stderr is what git (or ssh, or the server) prints; the four // marked "reproduced" come from local runs the integration suite repeats. const ROWS: ReadonlyArray<{ readonly name: string; readonly stderr: string; readonly access: GitCommandError["access"]; }> = [ { name: "prompt refused (reproduced: loopback 401)", stderr: "fatal: could not read Username for 'http://127.0.0.1:5000': terminal prompts disabled\n", access: "authentication", }, { name: "http 401 after credentials", stderr: "fatal: Authentication failed for 'https://github.com/o/n.git/'\n", access: "authentication", }, { name: "http 403 (reproduced: loopback 403)", stderr: "fatal: unable to access 'https://github.com/o/n.git/': The requested URL returned error: 403\n", access: "authentication", }, { name: "an http 500 is not an access refusal", stderr: "fatal: unable to access 'https://h/o/n.git/': The requested URL returned error: 500\n", access: undefined, }, { name: "ssh publickey refusal", stderr: "git@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.\n", access: "authentication", }, { name: "missing repository over file:// (reproduced)", stderr: "fatal: '/srv/nope' does not appear to be a git repository\nfatal: Could not read from remote repository.\n", access: "not-found", }, { name: "missing repository as a plain path", stderr: "fatal: repository '/srv/nope' does not exist\n", access: "not-found", }, { name: "GitHub over https", stderr: "remote: Repository not found.\nfatal: repository 'https://github.com/o/nope.git/' not found\n", access: "not-found", }, { name: "GitHub over ssh", stderr: "ERROR: Repository not found.\nfatal: Could not read from remote repository.\n", access: "not-found", }, { name: "http connect failure (reproduced)", stderr: "fatal: unable to access 'http://127.0.0.1:9/x.git/': Failed to connect to 127.0.0.1 port 9 after 0 ms: Couldn't connect to server\n", access: "unreachable", }, { name: "ssh connection refused (reproduced)", stderr: "ssh: connect to host 127.0.0.1 port 9: Connection refused\nfatal: Could not read from remote repository.\n", access: "unreachable", }, { name: "DNS over https", stderr: "fatal: unable to access 'https://nonexistent.invalid/x.git/': Could not resolve host: nonexistent.invalid\n", access: "unreachable", }, { name: "DNS over ssh", stderr: "ssh: Could not resolve hostname nonexistent.invalid: nodename nor servname provided, or not known\nfatal: Could not read from remote repository.\n", access: "unreachable", }, { name: "a TLS certificate failure is a configuration fault, not unreachable", stderr: "fatal: unable to access 'https://h/x.git/': SSL certificate problem: unable to get local issuer certificate\n", access: undefined, }, { name: "a TLS handshake failure carries no access", stderr: "fatal: unable to access 'https://h/x.git/': OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to h:443\n", access: undefined, }, { name: "a gnutls verification failure carries no access", stderr: "fatal: unable to access 'https://h/x.git/': server certificate verification failed. CAfile: none CRLfile: none\n", access: undefined, }, { name: "a schannel failure carries no access", stderr: "fatal: unable to access 'https://h/x.git/': schannel: SEC_E_UNTRUSTED_ROOT (0x80090325) - The certificate chain was issued by an authority that is not trusted.\n", access: undefined, }, { name: "a local EACCES has no parenthesis and is not authentication", stderr: "fatal: could not create work tree dir 'r': Permission denied\n", access: undefined, }, { name: "a non-empty destination is no refusal", stderr: "fatal: destination path 'r' already exists and is not an empty directory.\n", access: undefined, }, { name: "git's generic trailer alone is no refusal", stderr: "fatal: Could not read from remote repository.\n", access: undefined, }, ]; const ACCESS_MEMBERS: ReadonlyArray<{ readonly name: string; readonly call: (git: GitShape) => Effect.Effect; }> = [ { name: "clone", call: (git) => git.clone(cwd, { url: "/srv/r.git", directory: "r" }) }, { name: "fetch", call: (git) => git.fetch(cwd, { ref: "main" }) }, { name: "fetchAny", call: (git) => git.fetchAny(cwd, { ref: "main" }) }, { name: "fetchRefspecs", call: (git) => git.fetchRefspecs(cwd, { refspecs: ["main"] }) }, { name: "fetchUnshallow", call: (git) => git.fetchUnshallow(cwd) }, { name: "lsRemote", call: (git) => git.lsRemote(cwd, "origin") }, { name: "submoduleAdd", call: (git) => git.submoduleAdd(cwd, { url: "/srv/m.git", path: "m" }) }, { name: "submoduleUpdate", call: (git) => git.submoduleUpdate(cwd, { init: true }) }, ]; /** The error a member fails with when every spawn of it prints `stderr` and exits 128. */ const failWith = (member: (git: GitShape) => Effect.Effect, stderr: string) => Effect.flip(run(call(member), () => ({ exit: 128, stderr }))); for (const row of ROWS) { it.effect(`${row.name}: ${String(row.access)} on every access member`, () => Effect.gen(function* () { for (const member of ACCESS_MEMBERS) { const error = yield* failWith(member.call, row.stderr); assert.instanceOf(error, GitCommandError, member.name); assert.strictEqual(error.access, row.access, member.name); } }), ); } // okfit: git ends a failed submodule add with `fatal: clone of '' into submodule path '

' failed`, after // the line that says why. The access reading and `refusal` both answer from the line that says why. const SUBMODULE_CLONE_FAILED = "fatal: clone of 'https://github.com/o/n' into submodule path '/repo/m' failed\n"; const SUBMODULE_ROWS: ReadonlyArray<{ readonly name: string; readonly stderr: string; readonly access: GitCommandError["access"]; readonly refusal: string; }> = [ { name: "prompt refused", stderr: `Cloning into '/repo/m'...\nfatal: could not read Username for 'https://github.com': terminal prompts disabled\n${SUBMODULE_CLONE_FAILED}`, access: "authentication", refusal: "fatal: could not read Username for 'https://github.com': terminal prompts disabled", }, { name: "GitHub not found over https: git's own line beats the server's", stderr: `Cloning into '/repo/m'...\nremote: Repository not found.\nfatal: repository 'https://github.com/o/n/' not found\n${SUBMODULE_CLONE_FAILED}`, access: "not-found", refusal: "fatal: repository 'https://github.com/o/n/' not found", }, { name: "GitHub not found over ssh: the server's unprefixed line, not git's trailer", stderr: `Cloning into '/repo/m'...\nERROR: Repository not found.\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n${SUBMODULE_CLONE_FAILED}`, access: "not-found", refusal: "ERROR: Repository not found.", }, { name: "ssh publickey refusal", stderr: `Cloning into '/repo/m'...\ngit@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.\n${SUBMODULE_CLONE_FAILED}`, access: "authentication", refusal: "git@github.com: Permission denied (publickey).", }, { name: "two readings: authentication beats not-found, whichever line is first", stderr: `remote: Repository not found.\nfatal: Authentication failed for 'https://github.com/o/n/'\n${SUBMODULE_CLONE_FAILED}`, access: "authentication", refusal: "fatal: Authentication failed for 'https://github.com/o/n/'", }, { name: "no access refusal: the line before the submodule trailer", stderr: `Cloning into '/repo/m'...\nfatal: Remote branch nob not found in upstream origin\n${SUBMODULE_CLONE_FAILED}`, access: undefined, refusal: "fatal: Remote branch nob not found in upstream origin", }, ]; for (const row of SUBMODULE_ROWS) { it.effect(`submoduleAdd, ${row.name}: refusal is the line that says why`, () => Effect.gen(function* () { const error = yield* failWith( (git) => git.submoduleAdd(cwd, { url: "https://github.com/o/n", path: "m" }), row.stderr, ); assert.instanceOf(error, GitCommandError); assert.strictEqual(error.access, row.access); assert.strictEqual(error.refusal, row.refusal); }), ); } it.effect("control: push, pull and a local member fed a refusal carry no access", () => Effect.gen(function* () { const refusal = "fatal: Authentication failed for 'https://github.com/o/n.git/'\n"; for (const member of [ (git: GitShape) => git.push(cwd, { refspec: "main" }), (git: GitShape) => git.pull(cwd, { ref: "main" }), (git: GitShape) => git.checkout(cwd, "main"), ]) { const error = yield* failWith(member, refusal); assert.instanceOf(error, GitCommandError); assert.isUndefined(error.access); assert.isFalse("access" in error); } }), ); it.effect("an existing typed error still wins: not a repository, an unknown ref", () => Effect.gen(function* () { const notRepo = yield* failWith((git) => git.fetch(cwd, { ref: "main" }), "fatal: not a git repository\n"); assert.instanceOf(notRepo, NotARepositoryError); const missing = yield* failWith( (git) => git.fetch(cwd, { ref: "nope" }), "fatal: couldn't find remote ref nope\n", ); assert.instanceOf(missing, UnknownRefError); }), ); // A real clock: the hanging spawn is cut by the 1 ms run timeout. it.live("a timeout carries no access", () => Effect.gen(function* () { const error = yield* Effect.flip( run( Git.withRunOptions( call((git) => git.lsRemote(cwd, "origin")), { timeout: "1 millis" }, ), () => ({ hang: true, }), ), ); assert.instanceOf(error, GitCommandError); assert.include(error.detail ?? "", "timed out"); assert.isUndefined(error.access); }), ); }); describe("never prompts", () => { // Every member that can reach a remote spawns with git's prompt, askpass // and ssh BatchMode pins. clone is the new one; the rest are pinned in // Git.test.ts's NETWORK_MEMBERS table too, repeated here for the pins // themselves, which that table does not read. const MEMBERS: ReadonlyArray Effect.Effect]> = [ ["clone", (git) => git.clone(cwd, { url: "ssh://git@example.invalid/r.git", directory: "r" })], ["fetch", (git) => git.fetch(cwd, { ref: "main" })], ["fetchRefspecs", (git) => git.fetchRefspecs(cwd, { refspecs: ["main"] })], ["fetchUnshallow", (git) => git.fetchUnshallow(cwd)], ["lsRemote", (git) => git.lsRemote(cwd, "origin")], ["submoduleAdd", (git) => git.submoduleAdd(cwd, { url: "/srv/m.git", path: "m" })], ["submoduleUpdate", (git) => git.submoduleUpdate(cwd, { init: true })], ]; for (const [name, member] of MEMBERS) { it.effect(`${name} spawns with prompts, askpass and ssh prompts off`, () => Effect.gen(function* () { const seen: Array<{ readonly args: ReadonlyArray; readonly env: ChildProcess.StandardCommand["options"]["env"]; }> = []; const recording = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make((command) => { if (!ChildProcess.isStandardCommand(command)) return Effect.die("piped commands not scripted"); const args = command.args.map(String); seen.push({ args, env: command.options.env }); return Effect.succeed( ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(isSshProbe(args) ? 1 : 0)), isRunning: Effect.succeed(false), kill: () => Effect.void, stdin: Sink.drain, stdout: Stream.empty, stderr: Stream.empty, all: Stream.empty, getInputFd: () => Sink.drain, getOutputFd: () => Stream.empty, unref: Effect.succeed(Effect.void), }), ); }), ); yield* call(member).pipe( Effect.provide(GitOverMemory), Effect.provide(recording), Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord({}))), Effect.ignore, ); const invocation = seen.find((spawn) => !isSshProbe(spawn.args)); assert.isDefined(invocation); assert.strictEqual(invocation.env?.GIT_TERMINAL_PROMPT, "0"); assert.strictEqual(invocation.env?.GIT_ASKPASS, ""); assert.strictEqual(invocation.env?.SSH_ASKPASS_REQUIRE, "never"); assert.strictEqual(invocation.env?.GIT_SSH_COMMAND, "ssh -o BatchMode=yes"); }), ); } }); describe("aheadBehind", () => { it.effect("reads the left and right counts", () => Effect.gen(function* () { const counts = yield* run( call((git) => git.aheadBehind(cwd, "HEAD", "origin/main")), (args) => (args[0] === "rev-list" ? { stdout: "3\t1\n" } : { exit: 99 }), ); assert.deepStrictEqual(counts, AheadBehind.make({ ahead: 3, behind: 1 })); }), ); it.effect("an unknown ref is an UnknownRefError with the range label", () => Effect.gen(function* () { const error = yield* Effect.flip( run( call((git) => git.aheadBehind(cwd, "main", "nope")), () => ({ exit: 128, stderr: "fatal: bad revision 'main...nope'\n", }), ), ); assert.instanceOf(error, UnknownRefError); assert.strictEqual(error.ref, "main...nope"); }), ); it.effect("output that is not two counts is a GitCommandError with detail", () => Effect.gen(function* () { for (const stdout of ["3\n", "3\t1\t2\n", "x\t1\n", ""]) { const error = yield* Effect.flip( run( call((git) => git.aheadBehind(cwd, "a", "b")), () => ({ stdout }), ), ); assert.instanceOf(error, GitCommandError); assert.isDefined(error.detail); } }), ); it.effect("refuses an option-like ref before spawning", () => Effect.gen(function* () { const error = yield* Effect.flip( run( call((git) => git.aheadBehind(cwd, "HEAD", "--all")), neverSpawn, ), ); assert.instanceOf(error, GitCommandError); assert.strictEqual(error.kind, "refused"); }), ); }); describe("sparseCheckoutList", () => { const listWith = (byArgs: (args: ReadonlyArray) => ScriptResult) => run( call((git) => git.sparseCheckoutList(cwd)), byArgs, ); it.effect("not sparse is the disabled state, not a failure", () => Effect.gen(function* () { const state = yield* listWith((args) => args[0] === "sparse-checkout" ? { exit: 128, stderr: "fatal: this worktree is not sparse\n" } : { exit: 99 }, ); assert.deepStrictEqual(state, SparseCheckoutState.make({ enabled: false, cone: false, patterns: [] })); }), ); it.effect("an unset core.sparseCheckoutCone is cone mode", () => Effect.gen(function* () { const state = yield* listWith((args) => (args[0] === "sparse-checkout" ? { stdout: "a\nd e\n" } : { exit: 1 })); assert.deepStrictEqual(state, SparseCheckoutState.make({ enabled: true, cone: true, patterns: ["a", "d e"] })); }), ); it.effect("core.sparseCheckoutCone=false is pattern mode, read in git's boolean spellings", () => Effect.gen(function* () { for (const [value, cone] of [ ["false", false], ["no", false], ["0", false], ["true", true], ["On", true], ["1", true], ] as const) { const state = yield* listWith((args) => args[0] === "sparse-checkout" ? { stdout: "/a/\n!x\n" } : { stdout: `${value}\n` }, ); assert.strictEqual(state.cone, cone, value); // Pattern mode keeps file order and spelling; cone mode is canonical (sorted, normalized as git // normalizes a cone directory: no leading or trailing slash). assert.deepStrictEqual(state.patterns, cone ? ["!x", "a"] : ["/a/", "!x"], value); } }), ); it.effect("control: another 128 is a failure, and not-sparse text on another member is not absence", () => Effect.gen(function* () { const failure = yield* Effect.flip(listWith(() => ({ exit: 128, stderr: "fatal: something else\n" }))); assert.instanceOf(failure, GitCommandError); const set = yield* Effect.flip( run( call((git) => git.sparseCheckoutDisable(cwd)), () => ({ exit: 128, stderr: "fatal: this worktree is not sparse\n" }), ), ); assert.instanceOf(set, GitCommandError); }), ); }); describe("sparseCheckoutSet", () => { it.effect("reports the paths git left behind, read off its exit-0 warnings", () => Effect.gen(function* () { const result = yield* run( call((git) => git.sparseCheckoutSet(cwd, ["a"], { cone: true })), () => ({ stderr: [ "warning: The following paths are not up to date and were left despite sparse patterns:", "\tc/f", '\tq z/é"f', "", "After fixing the above paths, you may want to run `git sparse-checkout reapply`.", "warning: directory 'd e/' contains untracked files, but is not in the sparse-checkout cone", "", ].join("\n"), }), ); assert.deepStrictEqual( result, SparseCheckoutSetResult.make({ leftBehind: ["c/f", 'q z/é"f'], untrackedDirectories: ["d e/"] }), ); }), ); it.effect("a clean set leaves nothing behind", () => Effect.gen(function* () { const result = yield* run( call((git) => git.sparseCheckoutSet(cwd, ["a"], { cone: true })), () => ({}), ); assert.deepStrictEqual(result, SparseCheckoutSetResult.make({ leftBehind: [], untrackedDirectories: [] })); }), ); it.effect("a failing set still fails", () => Effect.gen(function* () { const error = yield* Effect.flip( run( call((git) => git.sparseCheckoutSet(cwd, ["a"], { cone: true })), () => ({ exit: 128, stderr: "fatal: not a git repository\n", }), ), ); assert.instanceOf(error, NotARepositoryError); }), ); }); describe("submoduleAdd options", () => { it.effect("passes -b and --name to git", () => Effect.gen(function* () { const seen: Array> = []; yield* run( call((git) => git.submoduleAdd(cwd, { url: "/srv/m.git", path: "m", branch: "main", name: "docs" })), (args) => { seen.push(args); return {}; }, ); assert.deepStrictEqual(seen, [["submodule", "add", "-b", "main", "--name", "docs", "--", "/srv/m.git", "m"]]); }), ); it.effect("refuses an option-like branch or name before spawning", () => Effect.gen(function* () { for (const options of [{ branch: "-x" }, { name: "--force" }]) { const error = yield* Effect.flip( run( call((git) => git.submoduleAdd(cwd, { url: "/srv/m.git", path: "m", ...options })), neverSpawn, ), ); assert.instanceOf(error, GitCommandError); assert.strictEqual(error.kind, "refused"); } }), ); }); describe("info/exclude", () => { /** A spawner answering `rev-parse --git-path info/exclude` with `answer`, and nothing else. */ const gitPath = (answer: string) => (args: ReadonlyArray) => args[0] === "rev-parse" && args[1] === "--git-path" ? { stdout: `${answer}\n` } : { exit: 99 }; it.effect("an absent file lists nothing", () => Effect.gen(function* () { const handle = yield* MemoryFileSystem.makeHandle({ "/repo/.git/HEAD": "ref: refs/heads/main\n" }); const patterns = yield* run( call((git) => git.infoExcludeList(cwd)), gitPath(".git/info/exclude"), handle.layer, ); assert.deepStrictEqual(patterns, []); }), ); it.effect("lists patterns without comments, blank lines, line breaks or a byte order mark", () => Effect.gen(function* () { const handle = yield* MemoryFileSystem.makeHandle({ "/repo/.git/info/exclude": "\uFEFF# git ls-files --others --exclude-from=.git/info/exclude\r\n\r\n*.log\r\n lead\r\n \r\nlast", }); const patterns = yield* run( call((git) => git.infoExcludeList(cwd)), gitPath(".git/info/exclude"), handle.layer, ); assert.deepStrictEqual(patterns, ["*.log", " lead", "last"]); }), ); it.effect("resolves git's answer against cwd, and takes an absolute answer as it is", () => Effect.gen(function* () { const handle = yield* MemoryFileSystem.makeHandle({ "/repo/.git/info/exclude": "relative\n", "/super/.git/modules/m/info/exclude": "absolute\n", }); const relative = yield* run( call((git) => git.infoExcludeList("/repo/sub")), gitPath("../.git/info/exclude"), handle.layer, ); const absolute = yield* run( call((git) => git.infoExcludeList("/super/m")), gitPath("/super/.git/modules/m/info/exclude"), handle.layer, ); assert.deepStrictEqual([relative, absolute], [["relative"], ["absolute"]]); }), ); it.effect("add creates info/ and the file, then is a no-op the second time", () => Effect.gen(function* () { const handle = yield* MemoryFileSystem.makeHandle({ "/repo/.git/HEAD": "ref: refs/heads/main\n" }); const add = run( call((git) => git.infoExcludeAdd(cwd, "vendor/docs/")), gitPath(".git/info/exclude"), handle.layer, ); assert.isTrue(yield* add); assert.strictEqual(handle.volume.text("/repo/.git/info/exclude"), "vendor/docs/\n"); assert.isFalse(yield* add); assert.strictEqual(handle.volume.text("/repo/.git/info/exclude"), "vendor/docs/\n"); }), ); it.effect("keeps the content, the byte order mark and CRLF line breaks, and ends an unterminated last line", () => Effect.gen(function* () { for (const [before, after] of [ ["\uFEFF# c\r\n*.log", "\uFEFF# c\r\n*.log\r\nvendor/\r\n"], ["a\nb\n", "a\nb\nvendor/\n"], ["a", "a\nvendor/\n"], ["", "vendor/\n"], ["\uFEFF", "\uFEFFvendor/\n"], ] as const) { const handle = yield* MemoryFileSystem.makeHandle({ "/repo/.git/info/exclude": before }); const added = yield* run( call((git) => git.infoExcludeAdd(cwd, "vendor/")), gitPath(".git/info/exclude"), handle.layer, ); assert.isTrue(added, JSON.stringify(before)); // Bytes, not `volume.text`: its decoder drops a leading byte order mark. const bytes = handle.volume.bytes("/repo/.git/info/exclude"); assert.strictEqual(new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes), after, JSON.stringify(before)); } }), ); it.effect("matches the exact line only: a CRLF copy is present, a prefix or a commented copy is not", () => Effect.gen(function* () { for (const [before, added] of [ ["x\r\nvendor/\r\n", false], ["\uFEFFvendor/\n", false], ["vendor/x\n", true], ["# vendor/\n", true], [" vendor/\n", true], ] as const) { const handle = yield* MemoryFileSystem.makeHandle({ "/repo/.git/info/exclude": before }); const result = yield* run( call((git) => git.infoExcludeAdd(cwd, "vendor/")), gitPath(".git/info/exclude"), handle.layer, ); assert.strictEqual(result, added, JSON.stringify(before)); } }), ); it.effect("refuses a pattern that is not one pattern line, before spawning", () => Effect.gen(function* () { const handle = yield* MemoryFileSystem.makeHandle(); for (const pattern of ["", " ", "a\nb", "a\r", "#comment"]) { const error = yield* Effect.flip( run( call((git) => git.infoExcludeAdd(cwd, pattern)), neverSpawn, handle.layer, ), ); assert.instanceOf(error, GitCommandError, JSON.stringify(pattern)); assert.strictEqual(error.kind, "refused"); } }), ); it.effect("an unreadable file is a GitCommandError with detail; outside a repository is NotARepositoryError", () => Effect.gen(function* () { const handle = yield* MemoryFileSystem.makeHandle({ "/repo/.git/info/exclude": MemoryFileSystem.directory() }); const unreadable = yield* Effect.flip( run( call((git) => git.infoExcludeList(cwd)), gitPath(".git/info/exclude"), handle.layer, ), ); assert.instanceOf(unreadable, GitCommandError); assert.include(unreadable.detail ?? "", "/repo/.git/info/exclude"); const outside = yield* Effect.flip( run( call((git) => git.infoExcludeList(cwd)), () => ({ exit: 128, stderr: "fatal: not a git repository\n" }), handle.layer, ), ); assert.instanceOf(outside, NotARepositoryError); }), ); });