TypeScript
fix(server): a git failure caused by a missing ref now says so (#17794)
Tristan Knightbe96c6c7006b
diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.tsindex 85670aa7ffb..ace13f40198 100644--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts@@ -1269,6 +1269,88 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {}),);+ it.effect.each([+ { action: "worktree add", detail: "git worktree add failed" },+ { action: "switch", detail: "git checkout failed" },+ ])(+ "reports a missing ref during $action with stable, redacted diagnostics",+ ({ action, detail }) =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ yield* initRepoWithCommit(cwd);+ const path = yield* Path.Path;+ const refName = "private/deleted-base";+ const locales: Array<string | undefined> = [];+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;+ const spawner = ChildProcessSpawner.make((command) => {+ if (+ ChildProcess.isStandardCommand(command) &&+ (command.args.includes("worktree") || command.args[0] === "checkout")+ ) {+ locales.push(command.options.env?.LC_ALL);+ }+ return delegate.spawn(command);+ });+ const driver = yield* makeGitVcsDriverCore().pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provide(layerServerConfig),+ );+ const error =+ action === "switch"+ ? yield* driver.switchRef({ cwd, refName }).pipe(Effect.flip)+ : yield* driver+ .createWorktree({+ cwd,+ refName,+ newRefName: "t3/new-thread",+ path: path.join(cwd, "worktree"),+ })+ .pipe(Effect.flip);++ assert.deepInclude(error, { _tag: "GitCommandError", detail, reason: "ref_not_found" });+ assert.include(error.message, `${detail} (ref_not_found)`);+ assert.notInclude(error.message, refName);+ assert.notInclude(yield* encodeGitCommandError(error), refName);+ assert.deepEqual(locales, ["C"]);+ assert.notProperty(error, "stderr");+ assert.notProperty(error, "args");+ }),+ );++ it.effect.each([+ // Git cannot tell a missing revision from a missing file in these.+ { label: "an argument that may be a path", args: ["log", "-1", "missing"] },+ {+ label: "a pathspec worded like a diagnostic",+ args: ["checkout", "HEAD", "--", "fatal: invalid reference: missing"],+ },+ // The tag exists; it names a tree, which git reports in the same words.+ {+ label: "a worktree from a non-commit",+ args: ["worktree", "add", "tree-worktree", "tree-tag"],+ },+ ])("leaves $label unclassified rather than calling it a missing ref", ({ args }) =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const driver = yield* GitVcsDriver.GitVcsDriver;+ yield* initRepoWithCommit(cwd);+ if (args.includes("tree-tag")) {+ yield* git(cwd, ["tag", "tree-tag", "HEAD^{tree}"]);+ }++ const error = yield* driver+ .execute({+ operation: "GitVcsDriver.test.ambiguousMissingName",+ cwd,+ args,+ env: { LC_ALL: "C" },+ })+ .pipe(Effect.flip);++ assert.notProperty(error, "reason");+ }),+ );+it.effect.each([{label: "a refused key",diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex 219467c2953..c3fb932c311 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -443,8 +443,18 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFai// Quoted-path forms only: an unquoted `fatal: <thing> already exists` also// covers tag and ref collisions, which are not path collisions.[/fatal: '[^']+' already exists|destination path .+ already exists/i, "path_already_exists"],+ // Ambiguous revision/path and pathspec failures can name files, so omit them.+ // Anchor to a diagnostic line to avoid matching quoted paths in other errors.+ [+ /^fatal: (?:invalid reference: |not a valid object name|needed a single revision|bad revision |'.+' is not a commit and a branch '.+' cannot be created from it)/im,+ "ref_not_found",+ ],];+// Existing non-commit objects share the missing-ref fatal diagnostic; Git+// distinguishes them with a separate error line.+const GIT_NOT_A_COMMIT_PATTERN = /^error: .+(?:, not a commit|expected commit type)/im;+// Hooks write to the same stream git does, and nothing distinguishes their text// from git's: a pre-push hook echoing "authentication failed" would otherwise// be read as a credential failure. `remote:` is deliberately excluded — git@@ -471,7 +481,9 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null {if (diagnostics.length === 0) return null;if (isNonRepositoryGitStderr(diagnostics)) return "not_a_repository";for (const [pattern, reason] of GIT_FAILURE_REASON_PATTERNS) {- if (pattern.test(diagnostics)) return reason;+ if (!pattern.test(diagnostics)) continue;+ if (reason === "ref_not_found" && GIT_NOT_A_COMMIT_PATTERN.test(diagnostics)) continue;+ return reason;}return null;}@@ -3500,7 +3512,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*const onCheckoutProgress = progress?.onCheckoutProgress;const checkoutWorkers = (yield* readConfigValue(input.cwd, "checkout.workers")) ?? "0";- yield* executeGit(+ yield* executeGitWithStableDiagnostics("GitVcsDriver.createWorktree",input.cwd,["-c", `checkout.workers=${checkoutWorkers}`, ...args],@@ -3511,7 +3523,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*? {// Git only prints checkout progress when stderr is a tty or the// delay elapsed. GIT_PROGRESS_DELAY=0 forces it through the pipe.- env: { GIT_PROGRESS_DELAY: "0", LC_ALL: "C" },+ env: { GIT_PROGRESS_DELAY: "0" },progress: {onStderrLine: (line) => {const parsed = parseGitCheckoutProgressLine(line);@@ -4032,10 +4044,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*yield* refuseOptionLikeRefName("GitVcsDriver.switchRef", input.cwd, checkoutArgs.at(-1));// A stale ref must not turn into a path checkout that discards local edits.- yield* executeGit("GitVcsDriver.switchRef.checkout", input.cwd, [...checkoutArgs, "--"], {- timeoutMs: 10_000,- fallbackErrorDetail: "git checkout failed",- });+ yield* executeGitWithStableDiagnostics(+ "GitVcsDriver.switchRef.checkout",+ input.cwd,+ [...checkoutArgs, "--"],+ {+ timeoutMs: 10_000,+ fallbackErrorDetail: "git checkout failed",+ },+ );const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, ["branch",diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.tsindex 2b48000cebd..715a5c42205 100644--- a/packages/contracts/src/git.test.ts+++ b/packages/contracts/src/git.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test";import * as Schema from "effect/Schema";import {+ GitCommandError,VcsCreateWorktreeInput,GitPreparePullRequestThreadInput,GitPreparePullRequestThreadResult,@@ -11,6 +12,7 @@ import {VcsStatusLocalResult,} from "./git.ts";+const decodeGitCommandError = Schema.decodeUnknownSync(Schema.toCodecJson(GitCommandError));const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput);const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(GitPreparePullRequestThreadInput,@@ -23,6 +25,24 @@ const decodeRunStackedActionResult = Schema.decodeUnknownSync(GitRunStackedActioconst decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);const decodeVcsStatusLocalResult = Schema.decodeUnknownSync(VcsStatusLocalResult);+describe("GitCommandError", () => {+ it("decodes an unknown failure reason as absent", () => {+ const error = decodeGitCommandError({+ _tag: "GitCommandError",+ operation: "GitVcsDriver.createWorktree",+ command: "git",+ cwd: "/repo",+ detail: "git worktree add failed",+ reason: "added_by_a_newer_server",+ });++ expect(error.reason).toBeUndefined();+ expect(error.message).toBe(+ "Git command failed in GitVcsDriver.createWorktree (/repo): git worktree add failed",+ );+ });+});+describe("VcsCreateWorktreeInput", () => {it("accepts omitted newRefName for existing-refName worktrees", () => {const parsed = decodeCreateWorktreeInput({diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.tsindex 2e4c4ada0a5..e719c0005d5 100644--- a/packages/contracts/src/git.ts+++ b/packages/contracts/src/git.ts@@ -1,6 +1,7 @@import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import {+ ForwardCompatibleOptional,NonNegativeInt,PositiveInt,ProjectId,@@ -347,9 +348,9 @@ export const VcsPullResult = Schema.Struct({});export type VcsPullResult = typeof VcsPullResult.Type;-// Git's stderr itself stays off the error: it echoes argv and remote URLs,-// which can hold credentials. The tag names the cause for logs and callers; it-// does not select a message.+// Git stderr can echo credentials from argv and remote URLs. Only a fixed+// reason reaches the error and its diagnostic suffix; newer, unknown reasons+// decode as absent through GitCommandError.export const GitCommandFailureReason = Schema.Literals(["authentication_failed","branch_already_exists",@@ -357,6 +358,7 @@ export const GitCommandFailureReason = Schema.Literals(["host_key_unverified","not_a_repository","path_already_exists",+ "ref_not_found","remote_unreachable","tag_would_be_clobbered",]);@@ -371,7 +373,7 @@ export class GitCommandError extends Schema.TaggedError<GitCommandError>()("GitCstdoutLength: Schema.optional(Schema.Number),stderrLength: Schema.optional(Schema.Number),outputLength: Schema.optional(Schema.Number),- reason: Schema.optional(GitCommandFailureReason),+ reason: ForwardCompatibleOptional(GitCommandFailureReason),detail: Schema.String,cause: Schema.optional(Schema.Defect()),}) {