// The recorder's signatures name `Git` and `GitShape` through the package's own name, so this entry's declarations // refer to the root's types instead of carrying a copy (`dtsExternals` in effected.toml); the runtime `Git` is local. import type { Git as GitService, GitShape } from "@effected/git"; import type { PlatformError, Scope } from "effect"; import { Effect, FileSystem, Layer, Path, Predicate, Schema, Semaphore } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { Git } from "../Git.js"; import { REPOSITORY_ENV_VARS } from "../internal/repositoryEnv.js"; import type { Collected } from "../internal/run.js"; import { runCollected } from "../internal/run.js"; import { CurrentSpawnTrace, SPAWN_CWD_VAR } from "../internal/spawnTrace.js"; /** * The config every fixture git process runs with, spelled as `GIT_CONFIG_COUNT` entries so it also reaches the * processes git spawns itself (a submodule add's internal clone among them). */ const FIXTURE_CONFIG: ReadonlyArray = [ ["protocol.file.allow", "always"], ["commit.gpgsign", "false"], ["tag.gpgsign", "false"], ["init.defaultBranch", "main"], ["advice.detachedHead", "false"], ["core.excludesFile", "/dev/null"], ["core.attributesFile", "/dev/null"], ]; const PROXY_VARS: ReadonlyArray = [ "http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", ]; const FIXTURE_ENV: Readonly> = { GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null", GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C", GIT_AUTHOR_NAME: "Effected Fixture", GIT_AUTHOR_EMAIL: "fixture@example.com", GIT_AUTHOR_DATE: "@978307200 +0000", GIT_COMMITTER_NAME: "Effected Fixture", GIT_COMMITTER_EMAIL: "fixture@example.com", GIT_COMMITTER_DATE: "@978307200 +0000", // ssh must read neither the host's ~/.ssh/config nor its known_hosts, and must never prompt. GIT_SSH_COMMAND: "ssh -F /dev/null -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=5", // Only the file transport (local paths and file://): a remote a test derives by mistake (a bare `owner/name` // expanded to https, say) is refused before any connection instead of reaching a real host. git reads it before // any protocol..allow. GitFixture.runOptionsWith widens it. GIT_ALLOW_PROTOCOL: "file", // An empty proxy variable is no proxy to curl; NO_PROXY="*" closes the rest. ...Object.fromEntries(PROXY_VARS.map((name) => [name, ""])), NO_PROXY: "*", no_proxy: "*", GIT_CONFIG_COUNT: String(FIXTURE_CONFIG.length), ...Object.fromEntries( FIXTURE_CONFIG.flatMap(([key, value], index) => [ [`GIT_CONFIG_KEY_${index}`, key], [`GIT_CONFIG_VALUE_${index}`, value], ]), ), }; /** * Host variables the fixture's own spawns remove from the inherited environment: git's repository variables (a * hook's `GIT_DIR` would otherwise redirect every command) and the ones that pick another ssh, transport allow-list, * editor or template directory. The keys {@link FIXTURE_ENV} sets itself are kept. */ const HOST_VARS: ReadonlyArray = [ ...REPOSITORY_ENV_VARS, "GIT_SSH", "GIT_SSH_VARIANT", "GIT_PROXY_COMMAND", "GIT_ALLOW_PROTOCOL", "GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "GIT_PAGER", "GIT_TEMPLATE_DIR", "GIT_EXEC_PATH", ].filter((name) => !(name in FIXTURE_ENV)); const SPAWN_ENV: Record = { ...Object.fromEntries(HOST_VARS.map((name) => [name, undefined])), ...FIXTURE_ENV, }; const FIXTURE_RUN_OPTIONS: { readonly env: Readonly>; readonly unset: ReadonlyArray; } = { env: FIXTURE_ENV, unset: REPOSITORY_ENV_VARS.filter((name) => !(name in FIXTURE_ENV)) }; /** * Options for `GitFixture.runOptionsWith`. * * @public */ export interface GitFixtureOptions { /** * The transports git may use, as `GIT_ALLOW_PROTOCOL` takes them (`file`, `https`, `ssh`, `git`, a remote helper's * name). Default `["file"]`, the fixture's own, which keeps a test off every real host. `"any"` sets no * `GIT_ALLOW_PROTOCOL` and removes an inherited one, so git falls back to its own `protocol..allow` rules. An * entry that is empty, or holds a `:` or whitespace, throws a `RangeError`: a wiring mistake, not input. */ readonly allowProtocol?: ReadonlyArray | "any"; } /** The fixture's run options with `options` applied. Throws on a malformed `allowProtocol` entry. */ const fixtureRunOptions = ( options: GitFixtureOptions = {}, ): { readonly env: Readonly>; readonly unset: ReadonlyArray } => { const allow = options.allowProtocol; if (allow === undefined) return FIXTURE_RUN_OPTIONS; if (allow === "any") { const { GIT_ALLOW_PROTOCOL: _dropped, ...env } = FIXTURE_ENV; return { env, unset: [...FIXTURE_RUN_OPTIONS.unset, "GIT_ALLOW_PROTOCOL"] }; } for (const name of allow) { if (name === "" || name.includes(":") || /\s/.test(name)) { throw new RangeError(`GitFixture.runOptionsWith: ${JSON.stringify(name)} is not a protocol name`); } } return { env: { ...FIXTURE_ENV, GIT_ALLOW_PROTOCOL: allow.join(":") }, unset: FIXTURE_RUN_OPTIONS.unset }; }; /** * Any `cause` as text, never throwing: an `Error`'s (or any object's) string `message`, a string itself, else * `String(cause)`, else its JSON, else its `Object.prototype.toString` tag. `String` alone throws "Cannot convert * object to primitive value" for an object with no usable `toString`, a Schema issue among them. */ const describeCause = (cause: unknown): string => { if (typeof cause === "string") return cause; if (Predicate.hasProperty(cause, "message") && typeof cause.message === "string") return cause.message; try { return String(cause); } catch { try { return JSON.stringify(cause) ?? Object.prototype.toString.call(cause); } catch { return Object.prototype.toString.call(cause); } } }; /** * A fixture git process or filesystem step failed. * * @remarks * `code` says which: `"git-failed"` (git exited non-zero, with `exitCode` and `stderr`), `"io-failed"` (a spawn or * filesystem call failed, the `PlatformError` in `cause`), `"empty-commit"` (a `LocalRemote` push whose files * change nothing, which would otherwise commit nothing and report the old tip as new), or `"trace-unreadable"` (a * line of the trace `GitFixture.recordSpawns` read is not a trace2 event, the decode failure in `cause`; a git killed * mid-write leaves one). Setup failing typed rather than as a defect lets a test assert on a refused push; a test * that only builds fixtures can treat it as fatal. * * @public */ export class GitFixtureError extends Schema.TaggedError()("GitFixtureError", { code: Schema.Literals(["git-failed", "io-failed", "empty-commit", "trace-unreadable"]), /** The directory the step ran in. */ cwd: Schema.String, /** The git argv (without `git`), or the filesystem operation and its path for `"io-failed"`. */ args: Schema.Array(Schema.String), exitCode: Schema.optionalKey(Schema.Number), stderr: Schema.optionalKey(Schema.String), cause: Schema.optionalKey(Schema.Defect()), /** The branch a `LocalRemote` push targeted; set for `"empty-commit"`. */ branch: Schema.optionalKey(Schema.String), }) { override get message(): string { const step = `${this.args.join(" ")} (in ${this.cwd})`; return this.code === "empty-commit" ? `git fixture: ${step} would commit nothing${this.branch === undefined ? "" : ` on branch ${this.branch}`}` : this.code === "git-failed" ? `git fixture: git ${step} exited ${String(this.exitCode)}: ${(this.stderr ?? "").trim()}` : this.code === "trace-unreadable" ? `git fixture: a trace2 line is not an event (${step}): ${describeCause(this.cause)}` : `git fixture: ${step} failed: ${describeCause(this.cause)}`; } } /** * Options for `LocalRemote.push`. * * @public */ export interface LocalRemotePushOptions { /** The branch to commit to; created from `main` when it does not exist yet. Default `"main"`. */ readonly branch?: string; /** Paths, relative to the repository root, to delete in the same commit. A missing path is ignored. */ readonly remove?: ReadonlyArray; } /** * Options for `GitFixture.makeRemote`. * * @public */ export interface MakeRemoteOptions { /** * The repository's name: the bare repository is `/.git` and its seed work tree `/-seed`, so * several remotes can share one directory. Default `"remote"`. */ readonly name?: string; } /** * A bare repository reached by a `file://` URL, plus the means to add commits to it, made by * `GitFixture.makeRemote`. * * @public */ export interface LocalRemote { /** The `file://` URL of the bare repository. */ readonly url: string; /** The bare repository's absolute path. */ readonly path: string; /** The commit the remote was seeded with, on `main`. */ readonly seedHead: string; /** The current tip of `branch` (default `"main"`) in the bare repository. */ readonly head: (branch?: string) => Effect.Effect; /** * Writes `files` (and deletes `options.remove`), commits them with `message` on `options.branch`, pushes the * branch, and returns the new commit's SHA. Fails `GitFixtureError` with code `"empty-commit"` when the commit would * change nothing. Concurrent pushes to one remote run one at a time. */ readonly push: ( files: Readonly>, message: string, options?: LocalRemotePushOptions, ) => Effect.Effect; } /** * One `Git` member call a `GitRecorder` recorded: the member's name and the arguments it was called with. * * @public */ export interface GitCall { /** The `GitShape` member called, such as `"sparseCheckoutSet"`. */ readonly member: keyof GitShape; /** The arguments, as passed. */ readonly args: ReadonlyArray; } /** * A call trace over a `Git` service, built by `GitFixture.recorder`: every member wrapped so that each call appends * one `GitCall` when its effect runs, then runs the member it wraps. * * @remarks * A call is recorded when its effect RUNS, not when the member is called: an effect built and never run (an * unchosen branch, a `catchTag` fallback that did not fire) leaves no trace, so "was not called" means "did not run". * * Provide `layer` at the OUTERMOST point, beside or over the `Git` layer the program uses, never by a nested * `Effect.provide` inside code that already has `Git`: layers memoize, so a nested provide of a layer that depends * on `Git` (the code under test's own service layer, say) reuses the outer, already-built instance, which captured * the unwrapped `Git`, and the recorder stays empty. okfit hit exactly that: its hand-written wrapper recorded * nothing, and an "X was not called" assertion passed for the wrong reason. Pair an absence assertion with a positive * one (`called` on a member the program must reach) so an unwired recorder fails the test. * * @public */ export interface GitRecorder { /** * `inner` with every member wrapped, for a hand-built service: `Layer.succeed(Git, recorder.wrap(Git.makeTest({ ... })))`. * Every function-valued member of `inner` is wrapped, so a member added to `GitShape` later is recorded too. */ readonly wrap: (inner: GitShape) => GitShape; /** * `Git` wrapped around the `Git` it is given, recording every call: `recorder.layer.pipe(Layer.provide(Git.layer))`. * A layer value bound once per recorder. */ readonly layer: Layer.Layer; /** A copy of the calls recorded so far, oldest first. */ readonly calls: ReadonlyArray; /** The argument lists of the recorded calls to `member`, oldest first; empty when it was not called. */ readonly callsTo: (member: keyof GitShape) => ReadonlyArray>; /** Whether `member` was called (its effect ran) at least once. */ readonly called: (member: keyof GitShape) => boolean; /** Forgets every call recorded so far. */ readonly clear: () => void; } const makeRecorder = (): GitRecorder => { const calls: Array = []; const wrap = (inner: GitShape): GitShape => { // Every key of the live shape, not a hand-kept list: a member added to GitShape is wrapped without an edit here. const wrapped: Record = {}; for (const [member, value] of Object.entries(inner)) { wrapped[member] = typeof value === "function" ? (...args: ReadonlyArray) => Effect.suspend(() => { calls.push({ member: member as keyof GitShape, args }); return value(...args); }) : value; } // Built key by key from `inner`, so it has exactly `inner`'s members with their own signatures. return wrapped as unknown as GitShape; }; return { wrap, layer: Layer.effect(Git, Effect.map(Effect.service(Git), wrap)), get calls() { return [...calls]; }, callsTo: (member) => calls.filter((call) => call.member === member).map((call) => call.args), called: (member) => calls.some((call) => call.member === member), clear: () => { calls.length = 0; }, }; }; /** * Replacement members for `GitFixture.faults`, keyed by `GitShape` member: each handler receives the member it * replaces (`original`) and the call's arguments, and returns what the member returns. Members with no handler are * left as they are. * * @remarks * A handler decides the call's whole outcome: call `original` to delegate, wrap it to delay or race it, or ignore it * to fail or answer without git. Its result must have the member's own type, so a fault can fail only with an error * the member already declares. * * @public */ export type GitFaultHandlers = { readonly [K in keyof GitShape]?: GitShape[K] extends (...args: infer A) => infer R ? (original: GitShape[K], ...args: A) => R : never; }; /** * A `Git` service with chosen members replaced by fault handlers, built by `GitFixture.faults`. * * @remarks * Provide `layer` at the OUTERMOST point, over the `Git` layer the program uses, as with `GitRecorder`: layers * memoize, so a nested `Effect.provide` inside code that already built a service over `Git` reuses that instance, * which captured the unfaulted `Git`, and the fault never fires. Pair a fault test with an assertion that the fault * ran (a counter in the handler, or a recorder over the faulted layer) so an unwired fault fails the test instead of * passing it. * * @public */ export interface GitFaults { /** * `inner` with each handled member replaced, for a hand-built service: * `Layer.succeed(Git, faults.wrap(Git.makeTest({ ... })))`. Every other member is `inner`'s own. Throws when a * handler names a member `inner` does not have, a wiring mistake. */ readonly wrap: (inner: GitShape) => GitShape; /** * `Git` with the faults applied to the `Git` it is given: `faults.layer.pipe(Layer.provide(Git.layer))`. A layer * value bound once per `faults(...)` call. */ readonly layer: Layer.Layer; } const makeFaults = (handlers: GitFaultHandlers): GitFaults => { const wrap = (inner: GitShape): GitShape => { const wrapped: Record = { ...inner }; // Erased to one shape: each handler is typed against its own member, which the loop cannot express. const entries = Object.entries(handlers) as ReadonlyArray< readonly [ string, ((original: unknown, ...args: ReadonlyArray) => Effect.Effect) | undefined, ] >; for (const [member, handler] of entries) { if (handler === undefined) continue; const original: unknown = Reflect.get(inner, member); if (typeof original !== "function" || typeof handler !== "function") { throw new TypeError(`GitFixture.faults: ${member} is not a Git member, or its handler is not a function`); } // Suspended so the handler runs when the call's effect runs, as the member itself would. wrapped[member] = (...args: ReadonlyArray) => Effect.suspend(() => handler(original, ...args)); } // `inner`'s members, with each handled one replaced by a function of the same signature. return wrapped as unknown as GitShape; }; return { wrap, layer: Layer.effect(Git, Effect.map(Effect.service(Git), wrap)) }; }; /** * Options for `GitFixture.recordSpawns`. * * @public */ export interface RecordSpawnsOptions { /** * Config keys to record for each spawn, as git's `trace2.configParams` patterns (`core.fsmonitor`, * `submodule.*.ignore`); none by default. A pattern holding `,` is two patterns to git. */ readonly config?: ReadonlyArray; } /** * One config entry a recorded spawn ran with, as git reports it in a trace2 `def_param` event. * * @public */ export interface GitSpawnConfig { /** The scope the entry came from: `"system"`, `"global"`, `"local"`, `"worktree"` or `"command"`. */ readonly scope: string; /** The key as git spells it. */ readonly key: string; readonly value: string; } /** * One git process recorded by `GitFixture.recordSpawns`. * * @public */ export interface GitSpawn { /** The argv as git reports it in the trace2 `start` event; `argv[0]` is the program as it was run. */ readonly argv: ReadonlyArray; /** * Whether git started this process itself (a submodule's status, a builtin re-run as `git-core/git`) rather than * the code under test. A child's argv carries no `-c` pair: git hands those to it in `GIT_CONFIG_PARAMETERS`. */ readonly child: boolean; /** * Every entry, in the order git read it, for the keys `RecordSpawnsOptions.config` names; empty when it names none. * A key set in several scopes appears once per scope, and the last one is the value in force. */ readonly config: ReadonlyArray; /** * The directory the process was started in. * * @remarks * For a `Git` member's own spawn (`child: false`) it is exact: the `cwd` the member was called with, as passed, * relative or not. For a child it is derived from what git reports, because no process reports its own directory: * the parent's directory joined with the `cd` git started the child with (a submodule's checkout runs in * `/`), or the parent's directory when git names none. A parent's directory, for this purpose, is * its worktree when it set one up (git moves there before running a repository command, and reports it as a real * path, so `/var/...` reads `/private/var/...` on macOS), else its own `cwd`. A child git starts through a shell or * through a program that is not git (an upload-pack, a dashed script) is reported in the directory that program * was started in; a directory such a program moves to itself is not seen. The join is textual, not normalized. */ readonly cwd: string; /** * The program that ran: the executable path git reports in its trace2 `cmd_path` event where its build reports one * (Linux and Windows builds with a runtime prefix), else `argv[0]` as it was run. So a `Git` member's own spawn * reads `git` on a host whose git reports no path (it was found on `PATH`), and a builtin git re-ran itself reads * as the absolute `.../git-core/git` it re-ran. */ readonly command: string; } /** * The trace2 event fields the recorder reads; every other field and event kind passes through unread. The fields * only some events carry are decoded as unknown and read only when they are strings, since another event kind may * use the same name for another shape (`value` is an object on `data_json`). */ const TraceEvent = Schema.Struct({ event: Schema.String, sid: Schema.String, argv: Schema.optionalKey(Schema.Array(Schema.String)), scope: Schema.optionalKey(Schema.String), param: Schema.optionalKey(Schema.String), value: Schema.optionalKey(Schema.Unknown), // `child_start`: the directory git starts the child in, and whether through a shell. cd: Schema.optionalKey(Schema.Unknown), use_shell: Schema.optionalKey(Schema.Unknown), // `def_repo`: the worktree git moved to; `cmd_path`: the executable's path. worktree: Schema.optionalKey(Schema.Unknown), path: Schema.optionalKey(Schema.Unknown), }); const decodeTraceLine = Schema.decodeUnknownEffect(Schema.fromJsonString(TraceEvent)); /** One `child_start` event a parent wrote, for matching to the child's own `start`. */ interface ChildStart { readonly argv: ReadonlyArray; readonly cd: string | undefined; readonly shell: boolean; matched: boolean; } /** What the trace says about one process, gathered across its events. */ interface TraceProcess { readonly config: Array; readonly children: Array; marker?: string; worktree?: string; cmdPath?: string; } const asString = (value: unknown): string | undefined => (typeof value === "string" ? value : undefined); /** `cd` taken from `dir`: as is when absolute, else joined textually. */ const within = (dir: string, cd: string): string => cd.startsWith("/") ? cd : `${dir.endsWith("/") ? dir.slice(0, -1) : dir}/${cd}`; /** Whether two argv tails (the program dropped: a child re-run reports its own path for it) are equal. */ const sameTail = (a: ReadonlyArray, b: ReadonlyArray): boolean => a.length === b.length && a.every((arg, index) => index === 0 || arg === b[index]); /** Parses a trace2 event file into its spawns, in start order, each with its `def_param` entries and directory. */ const parseTrace = (trace: string, text: string): Effect.Effect, GitFixtureError> => Effect.gen(function* () { const starts: Array<{ readonly sid: string; readonly argv: ReadonlyArray }> = []; const processes = new Map(); const processOf = (sid: string): TraceProcess => { const existing = processes.get(sid); if (existing !== undefined) return existing; const created: TraceProcess = { config: [], children: [] }; processes.set(sid, created); return created; }; for (const line of text.split("\n")) { if (line === "") continue; const event = yield* decodeTraceLine(line).pipe( Effect.mapError((cause) => GitFixtureError.make({ code: "trace-unreadable", cwd: trace, args: ["read", trace], cause }), ), ); const entry = processOf(event.sid); if (event.event === "start" && event.argv !== undefined) starts.push({ sid: event.sid, argv: event.argv }); if (event.event === "def_param" && event.param !== undefined) { if (event.param === SPAWN_CWD_VAR) { entry.marker = asString(event.value) ?? ""; } else { entry.config.push({ scope: event.scope ?? "", key: event.param, value: asString(event.value) ?? "" }); } } if (event.event === "child_start" && event.argv !== undefined) { entry.children.push({ argv: event.argv, cd: asString(event.cd), shell: event.use_shell === true, matched: false, }); } if (event.event === "def_repo") { const worktree = asString(event.worktree); if (worktree !== undefined) entry.worktree = worktree; } if (event.event === "cmd_path") { const path = asString(event.path); if (path !== undefined) entry.cmdPath = path; } } // A parent's start precedes its children's, so each directory is known before a child asks for it. const cwds = new Map(); return starts.map(({ sid, argv }): GitSpawn => { const entry = processOf(sid); // A child's sid is its parent's, a slash, then its own (trace2's `GIT_TRACE2_PARENT_SID`). const slash = sid.lastIndexOf("/"); let cwd: string; if (slash === -1) { cwd = entry.marker ?? ""; } else { const parentSid = sid.slice(0, slash); const parent = processOf(parentSid); const dir = parent.worktree ?? cwds.get(parentSid) ?? entry.marker ?? ""; const start = parent.children.find((child) => !child.matched && !child.shell && sameTail(child.argv, argv)); if (start !== undefined) start.matched = true; cwd = start?.cd === undefined ? dir : within(dir, start.cd); } cwds.set(sid, cwd); return { argv, child: slash !== -1, config: entry.config, cwd, command: entry.cmdPath ?? argv[0] ?? "", }; }); }); const recordSpawns = Effect.fn("GitFixture.recordSpawns")(function* ( effect: Effect.Effect, options: RecordSpawnsOptions = {}, ) { const fs = yield* FileSystem.FileSystem; const patterns = options.config ?? []; return yield* Effect.acquireUseRelease( fs .makeTempFile({ prefix: "effected-git-trace2-", suffix: ".json" }) .pipe(Effect.mapError(ioFailed("", "makeTempFile", "effected-git-trace2-"))), (trace) => Effect.gen(function* () { const result = yield* Git.withRunOptions(Effect.provideService(effect, CurrentSpawnTrace, true), { env: { GIT_TRACE2_EVENT: trace, // Every spawn's own directory, written into its trace by git and inherited by its children. GIT_TRACE2_ENV_VARS: SPAWN_CWD_VAR, ...(patterns.length === 0 ? {} : { GIT_TRACE2_CONFIG_PARAMS: patterns.join(",") }), }, // An inherited parent sid (a suite run from a git hook) would mark every spawn a child, and an // inherited pattern list would record keys nobody asked for. unset: ["GIT_TRACE2_PARENT_SID", ...(patterns.length === 0 ? ["GIT_TRACE2_CONFIG_PARAMS"] : [])], }); const text = yield* fs.readFileString(trace).pipe(Effect.mapError(ioFailed(trace, "readFileString", trace))); const spawns = yield* parseTrace(trace, text); return [result, spawns] as const; }), (trace) => Effect.ignore(fs.remove(trace, { force: true })), ); }); const ioFailed = (cwd: string, operation: string, target: string) => (cause: PlatformError.PlatformError): GitFixtureError => GitFixtureError.make({ code: "io-failed", cwd, args: [operation, target], cause }); /** One fixture git run, collected; fails only when git cannot be spawned. */ const spawnGit = ( cwd: string, args: ReadonlyArray, ): Effect.Effect => runCollected(ChildProcess.make("git", [...args], { cwd, env: SPAWN_ENV, extendEnv: true })).pipe( Effect.mapError((cause) => GitFixtureError.make({ code: "io-failed", cwd, args: [...args], cause })), ); /** One fixture git run that must succeed: its stdout without the trailing newline. */ const gitOut = ( cwd: string, args: ReadonlyArray, ): Effect.Effect => Effect.flatMap(spawnGit(cwd, args), (result) => result.exitCode === 0 ? Effect.succeed(result.stdout.trimEnd()) : Effect.fail( GitFixtureError.make({ code: "git-failed", cwd, args: [...args], exitCode: result.exitCode, stderr: result.stderr, }), ), ); /** * `relative` joined under `root`, or a defect when it is absolute or climbs out: a fixture path is the test author's * wiring, so an escape is a bug in the test, not a typed outcome. */ const inside = (path: Path.Path, root: string, relative: string): Effect.Effect => { const target = path.resolve(root, relative); const back = path.relative(root, target); return relative === "" || path.isAbsolute(relative) || back === "" || back.startsWith("..") ? Effect.die(new Error(`git fixture: path ${JSON.stringify(relative)} is not inside the repository`)) : Effect.succeed(target); }; /** * Test tooling for code that drives git against a remote: an isolated git environment, the `GitRunOptions` and layer * that hand it to `Git`'s live layer, and `makeRemote`, a seeded bare repository reached over `file://`. * * @remarks * Everything here spawns a real `git` (2.32 or later, for `GIT_CONFIG_GLOBAL`), on a POSIX host (`/dev/null` is the * empty config, ignore and ssh-config file). Compose the live layer with the fixture layer and one platform layer: * * The fixture's own spawns also remove git's repository variables (`GIT_DIR`, `GIT_INDEX_FILE` and the rest) from * the inherited environment, so a suite run from inside a git hook still builds its fixtures where it asked. * `runOptions` and `layer` carry the same removal (`unset`) for `Git`'s own spawns. * * @example * ```ts * import { Git } from "@effected/git"; * import { GitFixture } from "@effected/git/testing"; * import * as NodeServices from "@effect/platform-node/NodeServices"; * import { Effect, FileSystem, Layer } from "effect"; * * const TestLayer = Layer.mergeAll(Git.layer, GitFixture.layer).pipe(Layer.provideMerge(NodeServices.layer)); * * const program = Effect.gen(function* () { * const fs = yield* FileSystem.FileSystem; * const dir = yield* fs.makeTempDirectoryScoped(); * const remote = yield* GitFixture.makeRemote(dir, { "README.md": "hello\n" }); * const git = yield* Git; * yield* git.clone(dir, { url: remote.url, directory: "checkout" }); * }); * * Effect.runPromise(program.pipe(Effect.scoped, Effect.provide(TestLayer))); * ``` * * @public */ export class GitFixture { private constructor() {} /** * The isolated environment every fixture git process runs under, as plain variables: global and system config * ignored (`GIT_CONFIG_GLOBAL=/dev/null`, `GIT_CONFIG_NOSYSTEM=1`), a fixed author and committer identity and date * (2001-01-01T00:00:00Z, so a commit's SHA depends on its content alone), prompts off, `LC_ALL=C`, proxies cleared, * an ssh that reads no host config (`-F /dev/null`) and never prompts, and per-process config through * `GIT_CONFIG_COUNT`: `protocol.file.allow=always`, no signing, `main` as the initial branch, no detached-head * advice, and no host ignore or attributes file. Only the `file` transport is allowed * (`GIT_ALLOW_PROTOCOL=file`), so nothing a test runs reaches the network; `GitFixture.runOptionsWith` widens it. * * @remarks * `protocol.file.allow` travels in the environment, not in a repository's config, because git does not pass a * superproject's own config to a submodule add's internal clone, and refuses a `file://` submodule remote by * default. The environment entries reach that clone; a `git config protocol.file.allow always` in the superproject * does not. */ static readonly env: Readonly> = FIXTURE_ENV; /** * `GitFixture.env` as `GitRunOptions`, for `Git.withRunOptions` around one effect, with git's repository variables * (a hook's `GIT_DIR`, `GIT_INDEX_FILE`) removed from each spawn's inherited environment, so a test run from inside * a git hook still answers for the fixture's repositories. A `config` passed beside it is appended after the * fixture's own `GIT_CONFIG_COUNT` entries, so both apply. * * @remarks * Typed structurally rather than as `GitRunOptions`, which this entry point does not re-export; the value is * assignable to it. */ static readonly runOptions: { readonly env: Readonly>; readonly unset: ReadonlyArray; } = FIXTURE_RUN_OPTIONS; /** * `GitFixture.runOptions` with `options` applied: today, a wider or lifted transport allow-list * (`allowProtocol`) for a test that must speak `https` or `ssh` to a loopback server. With no options it is * `runOptions` itself. * * @remarks * The fixture allows the `file` transport alone (`GIT_ALLOW_PROTOCOL=file`), so a remote a test derives by mistake * never reaches a real host: a checkout declared only as `owner/name` that the code under test expands to * `https://github.com/owner/name` fails with `transport 'https' not allowed` instead of cloning from GitHub. Widen * it deliberately, for the one suite that needs it, and bind the layer to a `const` once, as in the example. * * Throws a `RangeError` for an `allowProtocol` entry that is empty or holds a `:` or whitespace. * * @example * ```ts * import * as NodeServices from "@effect/platform-node/NodeServices"; * import { Git } from "@effected/git"; * import { GitFixture } from "@effected/git/testing"; * import { Layer } from "effect"; * * // A suite that talks to a loopback http server: file and http, nothing else. * const HttpLayer = Layer.mergeAll( * Git.layer, * Git.layerRunOptions(GitFixture.runOptionsWith({ allowProtocol: ["file", "http"] })), * ).pipe(Layer.provideMerge(NodeServices.layer)); * ``` */ static runOptionsWith(options?: GitFixtureOptions): { readonly env: Readonly>; readonly unset: ReadonlyArray; } { return fixtureRunOptions(options); } /** * `Git.layerRunOptions(GitFixture.runOptions)`, bound once: compose it beside `Git.layer` so every `Git` member in * the program runs under the isolated environment. `Git`'s own pins (locale, prompt, askpass, the ssh batch-mode * pin) still win over it. * * @remarks * `Git.layerRunOptions(GitFixture.runOptions)` is the intended spelling when a suite needs the options merged with * its own (`Git.layerRunOptions({ ...GitFixture.runOptions, config: { ... } })`), and * `Git.withRunOptions(effect, GitFixture.runOptions)` around one effect; `runOptions` is typed structurally, and * both accept it. * * @example * ```ts * import * as NodeServices from "@effect/platform-node/NodeServices"; * import { Git } from "@effected/git"; * import { GitFixture } from "@effected/git/testing"; * import { Layer } from "effect"; * * // The fixture environment for every member, as this layer is: * const TestLayer = Layer.mergeAll(Git.layer, GitFixture.layer).pipe(Layer.provideMerge(NodeServices.layer)); * * // The same environment with one more config entry, spelled out: * const WithConfig = Layer.mergeAll( * Git.layer, * Git.layerRunOptions({ ...GitFixture.runOptions, config: { "core.autocrlf": "false" } }), * ).pipe(Layer.provideMerge(NodeServices.layer)); * ``` */ static readonly layer: Layer.Layer = Git.layerRunOptions(FIXTURE_RUN_OPTIONS); /** * A recorder of `Git` member calls: wrap a service with `wrap`, or provide `layer` over the live one, then assert * on `calls`, `callsTo` and `called`, including that a member was NOT called. Each call to `recorder()` is a fresh, * empty trace with its own layer. * * @remarks * Provide the recorder's layer at the outermost composition, over the `Git` layer itself: a nested * `Effect.provide` of a layer that depends on `Git` reuses the already-built outer instance, so the recorder never * sees the calls (see `GitRecorder`). * * @example * ```ts * import * as NodeServices from "@effect/platform-node/NodeServices"; * import { Git } from "@effected/git"; * import { GitFixture } from "@effected/git/testing"; * import { Effect, Layer } from "effect"; * * const recorder = GitFixture.recorder(); * // The recorder wraps the live Git, and the whole graph is provided once, at the edge. * const TestLayer = Layer.mergeAll(recorder.layer.pipe(Layer.provide(Git.layer)), GitFixture.layer).pipe( * Layer.provideMerge(NodeServices.layer), * ); * * const program = Effect.gen(function* () { * const git = yield* Git; * const state = yield* git.sparseCheckoutList("/work/docs"); * if (!state.enabled) yield* git.sparseCheckoutSet("/work/docs", ["docs"], { cone: true }); * }); * * // after running program under TestLayer: * console.log(recorder.called("sparseCheckoutList"), recorder.called("sparseCheckoutSet")); * // => true false (for a checkout that was already sparse) * ``` */ static readonly recorder: () => GitRecorder = makeRecorder; /** * A `Git` service with chosen members replaced: each handler receives the original member and the call's * arguments, so a test can make one member slow, racy or failing while every other member runs for real. Each call * to `faults(...)` builds its own layer. * * @remarks * Provide the layer at the outermost composition, over the `Git` layer itself, for the reason `GitFaults` gives. * It composes with a recorder over it, which records the calls the program made, faulted or not: * `recorder.layer.pipe(Layer.provide(faults.layer), Layer.provide(Git.layer))`. * * @example * ```ts * import * as NodeServices from "@effect/platform-node/NodeServices"; * import { Git } from "@effected/git"; * import { GitFixture } from "@effected/git/testing"; * import { Effect, Layer } from "effect"; * * let checked = 0; * const faults = GitFixture.faults({ * // The ref vanishes between the program's check and its use: answer "absent" from the first check on. * refExists: () => * Effect.sync(() => { * checked++; * return false; * }), * // Every other member, and this one's real work, run against the live Git. * currentBranch: (original, cwd) => Effect.andThen(Effect.yieldNow, original(cwd)), * }); * const TestLayer = Layer.mergeAll(faults.layer.pipe(Layer.provide(Git.layer)), GitFixture.layer).pipe( * Layer.provideMerge(NodeServices.layer), * ); * // run the program under TestLayer, then assert checked > 0 beside the program's own outcome. * ``` */ static readonly faults: (handlers: GitFaultHandlers) => GitFaults = makeFaults; /** * Runs `git ` in `cwd` under `GitFixture.env` and returns its stdout without the trailing newline, failing * `GitFixtureError` when git exits non-zero. For fixture setup a test does beside `makeRemote` (a work repository * to clone into, a commit made by hand), never for the code under test. */ static readonly git: ( cwd: string, args: ReadonlyArray, ) => Effect.Effect = Effect.fn("GitFixture.git")(gitOut); /** * Runs `effect` and records every git process its `Git` members spawn, git's own child processes included, through * git's trace2 event stream: returns the effect's result beside the spawns in the order they started. * * @remarks * The trace goes to a temporary file named in `GIT_TRACE2_EVENT`, set with `Git.withRunOptions` around `effect` * and removed afterwards. Because it is a run option, it composes with `GitFixture.layer` (the fixture environment * still applies) and with any `Git.withRunOptions` inside `effect`, `untrusted: true` among them, and it reaches the * locating reads under `ignoreRepositoryEnv` too. It sees only `Git` members' spawns: `GitFixture.git` and other * processes run outside the run options are not recorded. * * `argv` is what to assert untrusted mode on for a member that never reaches a vector: every spawn under the mode, * its discovery reads included, carries `-c core.fsmonitor=false`. The mode writes a key whose name holds `=` as a * `GIT_CONFIG_COUNT` entry instead, which no argv shows; name it in `options.config` and read it from `config`. * * A failure of `effect` fails the call and the spawns are lost; record `Effect.exit(effect)` to keep them. * * @example * ```ts * import { Git } from "@effected/git"; * import { GitFixture } from "@effected/git/testing"; * import { Effect } from "effect"; * * const program = Effect.gen(function* () { * const git = yield* Git; * const [, spawns] = yield* GitFixture.recordSpawns( * Git.withRunOptions(git.lsFiles("/path/to/repo"), { untrusted: true }), * ); * const own = spawns.filter((spawn) => !spawn.child); * console.log(own.every((spawn) => spawn.argv.includes("core.fsmonitor=false"))); * // => true * }); * ``` */ static readonly recordSpawns: ( effect: Effect.Effect, options?: RecordSpawnsOptions, ) => Effect.Effect], E | GitFixtureError, R | FileSystem.FileSystem> = recordSpawns; /** * Builds `/.git`, a bare repository on `main` holding `files` in one commit, and returns it as a * `LocalRemote`. `dir` is created when missing. * * @remarks * Commits are made in a work tree at `/-seed` and pushed over the `file` transport. Both directories * are removed when the scope closes, failure or not; `dir` itself is the caller's. A `files` key is a path relative * to the repository root; one that is absolute or climbs out of it dies as a defect. */ static readonly makeRemote: ( dir: string, files: Readonly>, options?: MakeRemoteOptions, ) => Effect.Effect< LocalRemote, GitFixtureError, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope > = Effect.fn("GitFixture.makeRemote")(function* ( dir: string, files: Readonly>, options: MakeRemoteOptions = {}, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const name = options.name ?? "remote"; const root = path.resolve(dir); const bare = yield* inside(path, root, `${name}.git`); const seed = yield* inside(path, root, `${name}-seed`); const run = (effect: Effect.Effect) => Effect.provideService(effect, ChildProcessSpawner.ChildProcessSpawner, spawner); const writeFiles = Effect.fn(function* (entries: Readonly>) { for (const [relative, content] of Object.entries(entries)) { const target = yield* inside(path, seed, relative); yield* fs .makeDirectory(path.dirname(target), { recursive: true }) .pipe(Effect.mapError(ioFailed(seed, "makeDirectory", path.dirname(target)))); yield* (typeof content === "string" ? fs.writeFileString(target, content) : fs.writeFile(target, content)).pipe( Effect.mapError(ioFailed(seed, "writeFile", target)), ); } }); // Removal is registered before anything is created, so a seed that fails half-way leaves nothing behind. yield* Effect.addFinalizer(() => Effect.ignore( Effect.all([ fs.remove(seed, { recursive: true, force: true }), fs.remove(bare, { recursive: true, force: true }), ]), ), ); yield* fs.makeDirectory(seed, { recursive: true }).pipe(Effect.mapError(ioFailed(root, "makeDirectory", seed))); yield* run(gitOut(root, ["init", "-q", "--bare", "-b", "main", bare])); yield* run(gitOut(seed, ["init", "-q", "-b", "main"])); const url = `file://${bare}`; yield* run(gitOut(seed, ["remote", "add", "origin", url])); yield* writeFiles(files); yield* run(gitOut(seed, ["add", "-A"])); yield* run(gitOut(seed, ["commit", "-q", "--allow-empty", "-m", "seed"])); yield* run(gitOut(seed, ["push", "-q", "origin", "main"])); const seedHead = yield* run(gitOut(seed, ["rev-parse", "HEAD"])); const lane = yield* Semaphore.make(1); const head = Effect.fn("LocalRemote.head")(function* (branch = "main") { return yield* run(gitOut(bare, ["rev-parse", "--verify", `refs/heads/${branch}^{commit}`])); }); const push = Effect.fn("LocalRemote.push")(function* ( more: Readonly>, message: string, pushOptions: LocalRemotePushOptions = {}, ) { const branch = pushOptions.branch ?? "main"; const exists = yield* run(spawnGit(seed, ["rev-parse", "--verify", "-q", `refs/heads/${branch}`])); yield* run( gitOut(seed, exists.exitCode === 0 ? ["checkout", "-q", branch] : ["checkout", "-q", "-b", branch, "main"]), ); yield* writeFiles(more); for (const relative of pushOptions.remove ?? []) { const target = yield* inside(path, seed, relative); yield* fs .remove(target, { recursive: true, force: true }) .pipe(Effect.mapError(ioFailed(seed, "remove", target))); } yield* run(gitOut(seed, ["add", "-A"])); if ((yield* run(gitOut(seed, ["status", "--porcelain"]))) === "") { return yield* GitFixtureError.make({ code: "empty-commit", cwd: seed, args: ["commit", "-m", message], branch, }); } yield* run(gitOut(seed, ["commit", "-q", "-m", message])); yield* run(gitOut(seed, ["push", "-q", "origin", branch])); return yield* run(gitOut(seed, ["rev-parse", "HEAD"])); }); return { url, path: bare, seedHead, head, push: (more, message, pushOptions) => Semaphore.withPermits(lane, 1)(push(more, message, pushOptions)), } satisfies LocalRemote; }); }