Skip to content

Commit be96c6c

Browse files
fix(server): a git failure caused by a missing ref now says so (pingdotgg#17794)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 28059f6 commit be96c6c

4 files changed

Lines changed: 132 additions & 11 deletions

File tree

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1269,6 +1269,88 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
12691269
}),
12701270
);
12711271

1272+
it.effect.each([
1273+
{ action: "worktree add", detail: "git worktree add failed" },
1274+
{ action: "switch", detail: "git checkout failed" },
1275+
])(
1276+
"reports a missing ref during $action with stable, redacted diagnostics",
1277+
({ action, detail }) =>
1278+
Effect.gen(function* () {
1279+
const cwd = yield* makeTmpDir();
1280+
yield* initRepoWithCommit(cwd);
1281+
const path = yield* Path.Path;
1282+
const refName = "private/deleted-base";
1283+
const locales: Array<string | undefined> = [];
1284+
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
1285+
const spawner = ChildProcessSpawner.make((command) => {
1286+
if (
1287+
ChildProcess.isStandardCommand(command) &&
1288+
(command.args.includes("worktree") || command.args[0] === "checkout")
1289+
) {
1290+
locales.push(command.options.env?.LC_ALL);
1291+
}
1292+
return delegate.spawn(command);
1293+
});
1294+
const driver = yield* makeGitVcsDriverCore().pipe(
1295+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1296+
Effect.provide(layerServerConfig),
1297+
);
1298+
const error =
1299+
action === "switch"
1300+
? yield* driver.switchRef({ cwd, refName }).pipe(Effect.flip)
1301+
: yield* driver
1302+
.createWorktree({
1303+
cwd,
1304+
refName,
1305+
newRefName: "t3/new-thread",
1306+
path: path.join(cwd, "worktree"),
1307+
})
1308+
.pipe(Effect.flip);
1309+
1310+
assert.deepInclude(error, { _tag: "GitCommandError", detail, reason: "ref_not_found" });
1311+
assert.include(error.message, `${detail} (ref_not_found)`);
1312+
assert.notInclude(error.message, refName);
1313+
assert.notInclude(yield* encodeGitCommandError(error), refName);
1314+
assert.deepEqual(locales, ["C"]);
1315+
assert.notProperty(error, "stderr");
1316+
assert.notProperty(error, "args");
1317+
}),
1318+
);
1319+
1320+
it.effect.each([
1321+
// Git cannot tell a missing revision from a missing file in these.
1322+
{ label: "an argument that may be a path", args: ["log", "-1", "missing"] },
1323+
{
1324+
label: "a pathspec worded like a diagnostic",
1325+
args: ["checkout", "HEAD", "--", "fatal: invalid reference: missing"],
1326+
},
1327+
// The tag exists; it names a tree, which git reports in the same words.
1328+
{
1329+
label: "a worktree from a non-commit",
1330+
args: ["worktree", "add", "tree-worktree", "tree-tag"],
1331+
},
1332+
])("leaves $label unclassified rather than calling it a missing ref", ({ args }) =>
1333+
Effect.gen(function* () {
1334+
const cwd = yield* makeTmpDir();
1335+
const driver = yield* GitVcsDriver.GitVcsDriver;
1336+
yield* initRepoWithCommit(cwd);
1337+
if (args.includes("tree-tag")) {
1338+
yield* git(cwd, ["tag", "tree-tag", "HEAD^{tree}"]);
1339+
}
1340+
1341+
const error = yield* driver
1342+
.execute({
1343+
operation: "GitVcsDriver.test.ambiguousMissingName",
1344+
cwd,
1345+
args,
1346+
env: { LC_ALL: "C" },
1347+
})
1348+
.pipe(Effect.flip);
1349+
1350+
assert.notProperty(error, "reason");
1351+
}),
1352+
);
1353+
12721354
it.effect.each([
12731355
{
12741356
label: "a refused key",

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -443,8 +443,18 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFai
443443
// Quoted-path forms only: an unquoted `fatal: <thing> already exists` also
444444
// covers tag and ref collisions, which are not path collisions.
445445
[/fatal: '[^']+' already exists|destination path .+ already exists/i, "path_already_exists"],
446+
// Ambiguous revision/path and pathspec failures can name files, so omit them.
447+
// Anchor to a diagnostic line to avoid matching quoted paths in other errors.
448+
[
449+
/^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,
450+
"ref_not_found",
451+
],
446452
];
447453

454+
// Existing non-commit objects share the missing-ref fatal diagnostic; Git
455+
// distinguishes them with a separate error line.
456+
const GIT_NOT_A_COMMIT_PATTERN = /^error: .+(?:, not a commit|expected commit type)/im;
457+
448458
// Hooks write to the same stream git does, and nothing distinguishes their text
449459
// from git's: a pre-push hook echoing "authentication failed" would otherwise
450460
// be read as a credential failure. `remote:` is deliberately excluded — git
@@ -471,7 +481,9 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null {
471481
if (diagnostics.length === 0) return null;
472482
if (isNonRepositoryGitStderr(diagnostics)) return "not_a_repository";
473483
for (const [pattern, reason] of GIT_FAILURE_REASON_PATTERNS) {
474-
if (pattern.test(diagnostics)) return reason;
484+
if (!pattern.test(diagnostics)) continue;
485+
if (reason === "ref_not_found" && GIT_NOT_A_COMMIT_PATTERN.test(diagnostics)) continue;
486+
return reason;
475487
}
476488
return null;
477489
}
@@ -3500,7 +3512,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
35003512
const onCheckoutProgress = progress?.onCheckoutProgress;
35013513

35023514
const checkoutWorkers = (yield* readConfigValue(input.cwd, "checkout.workers")) ?? "0";
3503-
yield* executeGit(
3515+
yield* executeGitWithStableDiagnostics(
35043516
"GitVcsDriver.createWorktree",
35053517
input.cwd,
35063518
["-c", `checkout.workers=${checkoutWorkers}`, ...args],
@@ -3511,7 +3523,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
35113523
? {
35123524
// Git only prints checkout progress when stderr is a tty or the
35133525
// delay elapsed. GIT_PROGRESS_DELAY=0 forces it through the pipe.
3514-
env: { GIT_PROGRESS_DELAY: "0", LC_ALL: "C" },
3526+
env: { GIT_PROGRESS_DELAY: "0" },
35153527
progress: {
35163528
onStderrLine: (line) => {
35173529
const parsed = parseGitCheckoutProgressLine(line);
@@ -4032,10 +4044,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
40324044
yield* refuseOptionLikeRefName("GitVcsDriver.switchRef", input.cwd, checkoutArgs.at(-1));
40334045

40344046
// A stale ref must not turn into a path checkout that discards local edits.
4035-
yield* executeGit("GitVcsDriver.switchRef.checkout", input.cwd, [...checkoutArgs, "--"], {
4036-
timeoutMs: 10_000,
4037-
fallbackErrorDetail: "git checkout failed",
4038-
});
4047+
yield* executeGitWithStableDiagnostics(
4048+
"GitVcsDriver.switchRef.checkout",
4049+
input.cwd,
4050+
[...checkoutArgs, "--"],
4051+
{
4052+
timeoutMs: 10_000,
4053+
fallbackErrorDetail: "git checkout failed",
4054+
},
4055+
);
40394056

40404057
const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [
40414058
"branch",

‎packages/contracts/src/git.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test";
22
import * as Schema from "effect/Schema";
33

44
import {
5+
GitCommandError,
56
VcsCreateWorktreeInput,
67
GitPreparePullRequestThreadInput,
78
GitPreparePullRequestThreadResult,
@@ -11,6 +12,7 @@ import {
1112
VcsStatusLocalResult,
1213
} from "./git.ts";
1314

15+
const decodeGitCommandError = Schema.decodeUnknownSync(Schema.toCodecJson(GitCommandError));
1416
const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput);
1517
const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(
1618
GitPreparePullRequestThreadInput,
@@ -23,6 +25,24 @@ const decodeRunStackedActionResult = Schema.decodeUnknownSync(GitRunStackedActio
2325
const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);
2426
const decodeVcsStatusLocalResult = Schema.decodeUnknownSync(VcsStatusLocalResult);
2527

28+
describe("GitCommandError", () => {
29+
it("decodes an unknown failure reason as absent", () => {
30+
const error = decodeGitCommandError({
31+
_tag: "GitCommandError",
32+
operation: "GitVcsDriver.createWorktree",
33+
command: "git",
34+
cwd: "/repo",
35+
detail: "git worktree add failed",
36+
reason: "added_by_a_newer_server",
37+
});
38+
39+
expect(error.reason).toBeUndefined();
40+
expect(error.message).toBe(
41+
"Git command failed in GitVcsDriver.createWorktree (/repo): git worktree add failed",
42+
);
43+
});
44+
});
45+
2646
describe("VcsCreateWorktreeInput", () => {
2747
it("accepts omitted newRefName for existing-refName worktrees", () => {
2848
const parsed = decodeCreateWorktreeInput({

‎packages/contracts/src/git.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as Effect from "effect/Effect";
22
import * as Schema from "effect/Schema";
33
import {
4+
ForwardCompatibleOptional,
45
NonNegativeInt,
56
PositiveInt,
67
ProjectId,
@@ -347,16 +348,17 @@ export const VcsPullResult = Schema.Struct({
347348
});
348349
export type VcsPullResult = typeof VcsPullResult.Type;
349350

350-
// Git's stderr itself stays off the error: it echoes argv and remote URLs,
351-
// which can hold credentials. The tag names the cause for logs and callers; it
352-
// does not select a message.
351+
// Git stderr can echo credentials from argv and remote URLs. Only a fixed
352+
// reason reaches the error and its diagnostic suffix; newer, unknown reasons
353+
// decode as absent through GitCommandError.
353354
export const GitCommandFailureReason = Schema.Literals([
354355
"authentication_failed",
355356
"branch_already_exists",
356357
"branch_checked_out_in_worktree",
357358
"host_key_unverified",
358359
"not_a_repository",
359360
"path_already_exists",
361+
"ref_not_found",
360362
"remote_unreachable",
361363
"tag_would_be_clobbered",
362364
]);
@@ -371,7 +373,7 @@ export class GitCommandError extends Schema.TaggedError<GitCommandError>()("GitC
371373
stdoutLength: Schema.optional(Schema.Number),
372374
stderrLength: Schema.optional(Schema.Number),
373375
outputLength: Schema.optional(Schema.Number),
374-
reason: Schema.optional(GitCommandFailureReason),
376+
reason: ForwardCompatibleOptional(GitCommandFailureReason),
375377
detail: Schema.String,
376378
cause: Schema.optional(Schema.Defect()),
377379
}) {

0 commit comments

Comments
 (0)