Extract cwd resolution into testable function

This commit is contained in:
Mohamed Boudra
2026-05-06 08:55:11 +07:00
parent 40543128f7
commit ea4d6bb7ce
2 changed files with 36 additions and 9 deletions

View File

@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { resolveImportCwd } from "./import.js";
describe("resolveImportCwd", () => {
it("uses the invoking process cwd when --cwd is omitted", () => {
expect(resolveImportCwd(undefined, "/Volumes/data/dev/rolepai")).toBe(
"/Volumes/data/dev/rolepai",
);
});
it("uses explicit --cwd when provided", () => {
expect(resolveImportCwd(" /tmp/project ", "/Volumes/data/dev/rolepai")).toBe("/tmp/project");
});
it("rejects an empty explicit --cwd", () => {
expect(() => resolveImportCwd(" ", "/Volumes/data/dev/rolepai")).toThrow(
expect.objectContaining({
code: "INVALID_CWD",
}),
);
});
});

View File

@@ -92,6 +92,18 @@ function parseImportLabels(labelFlags: string[] | undefined): Record<string, str
return labels;
}
export function resolveImportCwd(explicitCwd: string | undefined, defaultCwd: string): string {
const cwd = explicitCwd?.trim() ?? defaultCwd;
if (!cwd.trim()) {
throw {
code: "INVALID_CWD",
message: "--cwd cannot be empty",
details: "Provide a working directory path or omit --cwd",
} satisfies CommandError;
}
return cwd;
}
async function connectToDaemonOrThrow(
hostOption: string | undefined,
host: string,
@@ -124,14 +136,7 @@ export async function runImportCommand(
}
const provider = parseImportProvider(options.provider);
const cwd = options.cwd?.trim();
if (options.cwd !== undefined && !cwd) {
throw {
code: "INVALID_CWD",
message: "--cwd cannot be empty",
details: "Provide a working directory path or omit --cwd",
} satisfies CommandError;
}
const cwd = resolveImportCwd(options.cwd, process.cwd());
const labels = parseImportLabels(options.label);
const client = await connectToDaemonOrThrow(options.host, host);
@@ -140,7 +145,7 @@ export async function runImportCommand(
const agent = await client.importAgent({
provider,
sessionId,
...(cwd ? { cwd } : {}),
cwd,
...(Object.keys(labels).length > 0 ? { labels } : {}),
});