Skip to content

Commit cafa760

Browse files
xialongleesteipete
andauthored
fix(cli): show clean errors for missing input files (#105874)
* fix(cli): wrap readFileSync ENOENT with user-friendly messages and suppress cause leak * fix(secrets): type missing plan errors * style(secrets): format missing plan error branch --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent bd4714a commit cafa760

6 files changed

Lines changed: 91 additions & 5 deletions

File tree

‎src/cli/config-cli.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2396,6 +2396,15 @@ describe("config cli", () => {
23962396
expect(payload.configPath).not.toContain("~");
23972397
});
23982398

2399+
it("rejects --file when the file does not exist", async () => {
2400+
await expect(
2401+
runConfigCommand(["config", "patch", "--file", "/nonexistent/path/patch.json5"]),
2402+
).rejects.toThrow("__exit__:1");
2403+
2404+
expectErrorIncludes("--file not found: /nonexistent/path/patch.json5");
2405+
expect(mockWriteConfigFile).not.toHaveBeenCalled();
2406+
});
2407+
23992408
it("dry-runs pluginIntegration provider patches against manifest integration metadata", async () => {
24002409
const pluginId = "secret-provider-proof";
24012410
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-config-plugin-provider-"));

‎src/cli/config-cli.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import { diffConfigPaths } from "../gateway/config-diff.js";
4747
import { buildGatewayReloadPlan } from "../gateway/config-reload-plan.js";
4848
import { resolveGatewayReloadSettings } from "../gateway/config-reload-settings.js";
4949
import { danger, info, success, warn } from "../globals.js";
50+
import { hasErrnoCode } from "../infra/errors.js";
5051
import { parseStrictPositiveInteger } from "../infra/parse-finite-number.js";
5152
import { isBlockedObjectKey } from "../infra/prototype-keys.js";
5253
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
@@ -1505,7 +1506,19 @@ async function readConfigPatchInput(opts: ConfigPatchOptions): Promise<unknown>
15051506
throw configPatchModeError("provide exactly one of --file <path> or --stdin.");
15061507
}
15071508
const sourceLabel = stdin ? "--stdin" : "--file";
1508-
const raw = stdin ? await readStdinText() : fs.readFileSync(file as string, "utf8");
1509+
let raw: string;
1510+
if (stdin) {
1511+
raw = await readStdinText();
1512+
} else {
1513+
try {
1514+
raw = fs.readFileSync(file as string, "utf8");
1515+
} catch (err) {
1516+
if (hasErrnoCode(err, "ENOENT")) {
1517+
throw new Error(`--file not found: ${file}`, { cause: err });
1518+
}
1519+
throw err;
1520+
}
1521+
}
15091522
try {
15101523
return JSON5.parse(raw);
15111524
} catch (err) {

‎src/cli/config-set-input.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,14 @@ describe("config set input parsing", () => {
9696
);
9797
});
9898

99+
it("rejects --batch-file when the file does not exist", () => {
100+
expect(() =>
101+
parseBatchSource({
102+
batchFile: "/nonexistent/path/batch.json5",
103+
}),
104+
).toThrow("--batch-file not found: /nonexistent/path/batch.json5");
105+
});
106+
99107
it("rejects malformed --batch-file payloads", () => {
100108
withBatchFile("openclaw-config-set-input-invalid-", "{}", (batchPath) => {
101109
expect(() =>

‎src/cli/config-set-input.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
normalizeStringifiedOptionalString,
66
} from "@openclaw/normalization-core/string-coerce";
77
import JSON5 from "json5";
8+
import { hasErrnoCode } from "../infra/errors.js";
89

910
export type ConfigSetOptions = {
1011
strictJson?: boolean;
@@ -136,6 +137,14 @@ export function parseBatchSource(opts: ConfigSetOptions): ConfigSetBatchEntry[]
136137
if (!pathname) {
137138
throw new Error("--batch-file must not be empty.");
138139
}
139-
const raw = fs.readFileSync(pathname, "utf8");
140+
let raw: string;
141+
try {
142+
raw = fs.readFileSync(pathname, "utf8");
143+
} catch (err) {
144+
if (hasErrnoCode(err, "ENOENT")) {
145+
throw new Error(`--batch-file not found: ${pathname}`, { cause: err });
146+
}
147+
throw err;
148+
}
140149
return parseBatchEntries(raw, "--batch-file");
141150
}

‎src/cli/secrets-cli.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,37 @@ describe("secrets CLI", () => {
399399
}, "{invalid json");
400400
});
401401

402+
it("rejects --from when the plan file does not exist", async () => {
403+
await expect(
404+
createProgram().parseAsync(["secrets", "apply", "--from", "/nonexistent/path/plan.json"], {
405+
from: "user",
406+
}),
407+
).rejects.toThrow("__exit__:1");
408+
409+
const errorOutput = runtimeErrors.join("\n");
410+
expect(errorOutput).toContain("Secrets plan file not found: /nonexistent/path/plan.json");
411+
expect(errorOutput).not.toContain("ENOENT");
412+
expect(runSecretsApply).not.toHaveBeenCalled();
413+
});
414+
415+
it("preserves causes for unrelated apply errors with a similar message", async () => {
416+
await withPlanFile(async (planPath) => {
417+
runSecretsApply.mockRejectedValueOnce(
418+
new Error("Secrets plan file not found during apply", {
419+
cause: new Error("provider diagnostic"),
420+
}),
421+
);
422+
423+
await expect(
424+
createProgram().parseAsync(["secrets", "apply", "--from", planPath], { from: "user" }),
425+
).rejects.toThrow("__exit__:1");
426+
427+
expect(runtimeErrors.join("\n")).toContain(
428+
"Secrets plan file not found during apply | provider diagnostic",
429+
);
430+
});
431+
});
432+
402433
it("does not print skipped-exec note when apply dry-run skippedExecRefs is zero", async () => {
403434
await withPlanFile(async (planPath) => {
404435
runSecretsApply.mockResolvedValue(createSecretsApplyResult({ resolvabilityComplete: false }));

‎src/cli/secrets-cli.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { Command } from "commander";
33
import { formatDocsLink } from "../../packages/terminal-core/src/links.js";
44
import { theme } from "../../packages/terminal-core/src/theme.js";
55
import { danger } from "../globals.js";
6-
import { formatErrorMessage } from "../infra/errors.js";
6+
import { formatErrorMessage, hasErrnoCode } from "../infra/errors.js";
77
import { defaultRuntime } from "../runtime.js";
88
import type { SecretsApplyPlan } from "../secrets/plan.js";
99
import { createLazyImportLoader } from "../shared/lazy-promise.js";
@@ -46,13 +46,25 @@ const secretsApplyLoader = createLazyImportLoader<SecretsApplyModule>(
4646
() => import("../secrets/apply.js"),
4747
);
4848

49+
class SecretsPlanFileNotFoundError extends Error {}
50+
4951
async function readPlanFile(pathname: string): Promise<SecretsApplyPlan> {
5052
// Apply consumes a generated plan shape, not arbitrary JSON.
5153
const [{ readFileSync }, { isSecretsApplyPlan }] = await Promise.all([
5254
fsModuleLoader.load(),
5355
import("../secrets/plan.js"),
5456
]);
55-
const raw = readFileSync(pathname, "utf8");
57+
let raw: string;
58+
try {
59+
raw = readFileSync(pathname, "utf8");
60+
} catch (err) {
61+
if (hasErrnoCode(err, "ENOENT")) {
62+
throw new SecretsPlanFileNotFoundError(`Secrets plan file not found: ${pathname}`, {
63+
cause: err,
64+
});
65+
}
66+
throw err;
67+
}
5668
let parsed: unknown;
5769
try {
5870
parsed = JSON.parse(raw);
@@ -333,9 +345,13 @@ export function registerSecretsCli(program: Command): void {
333345
: "Secrets apply: no changes.",
334346
);
335347
} catch (err) {
348+
// The missing-plan wrapper already carries a user-facing message. Keep its
349+
// ENOENT cause available to diagnostics without rendering the raw filesystem error.
350+
const message =
351+
err instanceof SecretsPlanFileNotFoundError ? err.message : formatErrorMessage(err);
336352
defaultRuntime.error(
337353
danger(
338-
`Secrets apply failed: ${formatErrorMessage(err)}. Re-run ${formatCliCommand("openclaw secrets apply --from <path> --dry-run")} to inspect the plan without writing.`,
354+
`Secrets apply failed: ${message}. Re-run ${formatCliCommand("openclaw secrets apply --from <path> --dry-run")} to inspect the plan without writing.`,
339355
),
340356
);
341357
defaultRuntime.exit(1);

0 commit comments

Comments
 (0)