commit 2201a5357abeb7ccac3b40016e77db72d988e375
parent 8bc7bd9c7d3730ec26cb59a0d706126a5669d9da
Author: Henry Unite <unitehenry@gmail.com>
Date: Sun, 15 Nov 2026 19:40:51 +0000
refactor: make fs and exec operations async
Replace synchronous fs and child_process calls with awaited promises throughout logging, cleanup, prompt handling, shell wrapping, and the clear-openpod command. Update unit tests to await the async APIs and cover the new helpers.
Diffstat:
14 files changed, 287 insertions(+), 319 deletions(-)
diff --git a/command/clear.ts b/command/clear.ts
@@ -1,18 +1,20 @@
import type { OpenpodContext } from "../context";
-import * as fs from "node:fs";
+import { readdir, rm } from "node:fs/promises";
+
+import { exists } from "../context/fs";
export async function clear(deps: OpenpodContext): Promise<void> {
const { logger, openpodRoot } = deps;
- logger.log("[clear] starting full openpod cleanup");
+ await logger.log("[clear] starting full openpod cleanup");
try {
- if (!fs.existsSync(openpodRoot)) {
- logger.log("[clear] openpod root does not exist");
+ if (!(await exists(openpodRoot))) {
+ await logger.log("[clear] openpod root does not exist");
return;
}
// Clean up each session/pod individually (stops + deletes lima + removes dir)
- const entries = fs.readdirSync(openpodRoot, { withFileTypes: true });
+ const entries = await readdir(openpodRoot, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const sessionID = entry.name;
@@ -21,9 +23,9 @@ export async function clear(deps: OpenpodContext): Promise<void> {
}
// Remove the root directory entirely (includes .log etc.)
- fs.rmSync(openpodRoot, { recursive: true, force: true });
- logger.log(`[clear] removed entire directory ${openpodRoot}`);
+ await rm(openpodRoot, { recursive: true, force: true });
+ await logger.log(`[clear] removed entire directory ${openpodRoot}`);
} catch (err) {
- logger.log(`[clear] error during cleanup: ${err}`);
+ await logger.log(`[clear] error during cleanup: ${err}`);
}
}
diff --git a/command/index.ts b/command/index.ts
@@ -14,7 +14,7 @@ export async function registerCommand(
deps: OpenpodContext,
): Promise<void> {
const { logger } = deps;
- logger.log("registering commands");
+ await logger.log("registering commands");
await ctx.command.transform((editor) => {
editor.add({
diff --git a/context/cleanup.test.ts b/context/cleanup.test.ts
@@ -2,27 +2,24 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
-import { spawnSync } from "node:child_process";
import { initCleanup } from "./cleanup";
+import { exec } from "./exec";
-vi.mock("node:child_process", async (importOriginal) => {
- const actual = await importOriginal<typeof import("node:child_process")>();
- return {
- ...actual,
- spawnSync: vi.fn(),
- };
-});
+vi.mock("./exec", () => ({
+ exec: vi.fn(),
+}));
describe("cleanup", () => {
let tempRoot: string;
+ const execMock = vi.mocked(exec);
beforeEach(() => {
vi.clearAllMocks();
- (
- spawnSync as unknown as { mockReturnValue: (val: unknown) => void }
- ).mockReturnValue({
+ execMock.mockResolvedValue({
status: 0,
+ stdout: "",
+ stderr: "",
});
tempRoot = path.join(
os.tmpdir(),
@@ -54,7 +51,7 @@ describe("cleanup", () => {
// @ts-expect-error testing runtime guard
await cleanup.execute(undefined);
- expect(spawnSync).not.toHaveBeenCalled();
+ expect(execMock).not.toHaveBeenCalled();
});
it("attempts lima stop/delete", async () => {
@@ -62,20 +59,16 @@ describe("cleanup", () => {
const sessionID = "test-session";
await cleanup.execute(sessionID);
- expect(spawnSync).toHaveBeenCalledWith(
- "limactl",
- ["stop", sessionID, "--force"],
- {
- stdio: "ignore",
- },
- );
- expect(spawnSync).toHaveBeenCalledWith(
- "limactl",
- ["delete", sessionID, "--force"],
- {
- stdio: "ignore",
- },
- );
+ expect(execMock).toHaveBeenCalledWith("limactl", [
+ "stop",
+ sessionID,
+ "--force",
+ ]);
+ expect(execMock).toHaveBeenCalledWith("limactl", [
+ "delete",
+ sessionID,
+ "--force",
+ ]);
});
it("removes existing pod directory", async () => {
diff --git a/context/cleanup.ts b/context/cleanup.ts
@@ -1,7 +1,8 @@
-import * as fs from "node:fs";
-import { spawnSync } from "node:child_process";
+import { rm } from "node:fs/promises";
import * as path from "node:path";
+import { exec } from "./exec";
+import { exists } from "./fs";
import type { Logger } from "./logger";
export type Cleanup = {
@@ -9,42 +10,33 @@ export type Cleanup = {
};
export function initCleanup(openpodRoot: string, logger?: Logger): Cleanup {
- const log = (message: string, level?: string) =>
- logger?.log?.(message, level);
+ const log = async (message: string, level?: string): Promise<void> => {
+ await logger?.log?.(message, level);
+ };
- function stopLimaInstance(limaName: string): void {
+ async function stopLimaInstance(limaName: string): Promise<void> {
// best-effort stop (ignore errors)
- try {
- spawnSync("limactl", ["stop", limaName, "--force"], { stdio: "ignore" });
- log(`[cleanup] stopped ${limaName} (if running)`);
- } catch {
- // ignore
- }
+ await exec("limactl", ["stop", limaName, "--force"]);
+ await log(`[cleanup] stopped ${limaName} (if running)`);
}
- function deleteLimaInstance(limaName: string): void {
- // delete the lima instance
- try {
- const result = spawnSync("limactl", ["delete", limaName, "--force"], {
- stdio: "ignore",
- });
- log(`[cleanup] limactl delete ${limaName} exited with ${result.status}`);
- } catch (err) {
- log(`[cleanup] limactl delete error for ${limaName}: ${err}`);
- }
+ async function deleteLimaInstance(limaName: string): Promise<void> {
+ const result = await exec("limactl", ["delete", limaName, "--force"]);
+ await log(
+ `[cleanup] limactl delete ${limaName} exited with ${result.status}`,
+ );
}
- function removePodDirectory(podDir: string): void {
- // remove the openpod directory
+ async function removePodDirectory(podDir: string): Promise<void> {
try {
- if (fs.existsSync(podDir)) {
- fs.rmSync(podDir, { recursive: true, force: true });
- log(`[cleanup] removed directory ${podDir}`);
+ if (await exists(podDir)) {
+ await rm(podDir, { recursive: true, force: true });
+ await log(`[cleanup] removed directory ${podDir}`);
} else {
- log(`[cleanup] directory did not exist: ${podDir}`);
+ await log(`[cleanup] directory did not exist: ${podDir}`);
}
} catch (err) {
- log(`[cleanup] failed to remove ${podDir}: ${err}`);
+ await log(`[cleanup] failed to remove ${podDir}: ${err}`);
}
}
@@ -54,11 +46,11 @@ export function initCleanup(openpodRoot: string, logger?: Logger): Cleanup {
const limaName = sessionID;
const podDir = path.join(openpodRoot, sessionID);
- log(`[cleanup] starting for ${sessionID}`);
+ await log(`[cleanup] starting for ${sessionID}`);
- stopLimaInstance(limaName);
- deleteLimaInstance(limaName);
- removePodDirectory(podDir);
+ await stopLimaInstance(limaName);
+ await deleteLimaInstance(limaName);
+ await removePodDirectory(podDir);
}
return { execute };
diff --git a/context/index.ts b/context/index.ts
@@ -1,7 +1,7 @@
import * as os from "node:os";
import * as path from "node:path";
-import { execSync } from "node:child_process";
+import { exec } from "./exec";
import { initLogger, type Logger } from "./logger";
import { initCleanup, type Cleanup } from "./cleanup";
@@ -17,24 +17,16 @@ export async function init(): Promise<OpenpodContext> {
const logger = initLogger(openpodRoot);
const cleanup = initCleanup(openpodRoot, logger);
- function isCommandAvailable(command: string): boolean {
- try {
- if (process.platform === "win32") {
- execSync(`where ${command}`, { stdio: "ignore" });
- } else {
- execSync(`command -v ${command}`, {
- stdio: "ignore",
- shell: "/bin/sh",
- });
- }
- return true;
- } catch {
- return false;
- }
+ async function isCommandAvailable(command: string): Promise<boolean> {
+ const result =
+ process.platform === "win32"
+ ? await exec("where", [command])
+ : await exec("/bin/sh", ["-c", `command -v ${command}`]);
+ return result.status === 0;
}
- if (!isCommandAvailable("limactl")) {
- logger.log(
+ if (!(await isCommandAvailable("limactl"))) {
+ await logger.log(
"`limactl` is not installed. Lima is required for openpod. See https://lima-vm.io/",
"error",
);
diff --git a/context/logger.test.ts b/context/logger.test.ts
@@ -32,17 +32,17 @@ describe("logger", () => {
expect(typeof logger.log).toBe("function");
});
- it("creates .log directory and log file on first log", () => {
+ it("creates .log directory and log file on first log", async () => {
const logger = initLogger(tempRoot);
- logger.log("test message");
+ await logger.log("test message");
expect(fs.existsSync(path.join(tempRoot, ".log"))).toBe(true);
expect(fs.existsSync(logFile)).toBe(true);
});
- it("appends log entry with correct format", () => {
+ it("appends log entry with correct format", async () => {
const logger = initLogger(tempRoot);
- logger.log("hello world");
+ await logger.log("hello world");
const content = fs.readFileSync(logFile, "utf8");
expect(content).toContain("[openpod] hello world");
@@ -51,18 +51,18 @@ describe("logger", () => {
);
});
- it("includes level prefix for non-info levels", () => {
+ it("includes level prefix for non-info levels", async () => {
const logger = initLogger(tempRoot);
- logger.log("error happened", "error");
+ await logger.log("error happened", "error");
const content = fs.readFileSync(logFile, "utf8");
expect(content).toContain("[error] error happened");
});
- it("appends multiple logs", () => {
+ it("appends multiple logs", async () => {
const logger = initLogger(tempRoot);
- logger.log("first");
- logger.log("second");
+ await logger.log("first");
+ await logger.log("second");
const content = fs.readFileSync(logFile, "utf8");
expect(content).toContain("first");
diff --git a/context/logger.ts b/context/logger.ts
@@ -1,20 +1,20 @@
-import * as fs from "node:fs";
+import { appendFile, mkdir } from "node:fs/promises";
import * as path from "node:path";
export type Logger = {
- log: (message: string, level?: string) => void;
+ log: (message: string, level?: string) => Promise<void>;
};
export function initLogger(openpodRoot: string): Logger {
const logDir = path.join(openpodRoot, ".log");
const logFile = path.join(logDir, "openpod.log");
- function log(message: string, level: string = "info"): void {
+ async function log(message: string, level: string = "info"): Promise<void> {
try {
- fs.mkdirSync(logDir, { recursive: true });
+ await mkdir(logDir, { recursive: true });
const timestamp = new Date().toISOString();
const levelPart = level === "info" ? "" : `[${level}] `;
- fs.appendFileSync(
+ await appendFile(
logFile,
`[${timestamp}] [openpod] ${levelPart}${message}\n`,
);
diff --git a/controller/index.ts b/controller/index.ts
@@ -32,7 +32,7 @@ export async function registerController(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
if (err?.name !== "AbortError") {
- deps.logger.log(`event subscription error: ${err}`);
+ await deps.logger.log(`event subscription error: ${err}`);
}
}
})();
diff --git a/prompt/handle.test.ts b/prompt/handle.test.ts
@@ -10,37 +10,40 @@ import {
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
-import { spawnSync } from "node:child_process";
import type { OpenpodContext } from "../context";
import { init } from "../context";
+import { exec } from "../context/exec";
import { handle } from "./handle";
-vi.mock("node:child_process", async (importOriginal) => {
- const actual = await importOriginal<typeof import("node:child_process")>();
- return {
- ...actual,
- spawnSync: vi.fn(),
- };
-});
+vi.mock("../context/exec", () => ({
+ exec: vi.fn(),
+}));
describe("handle", () => {
let mockMove: ReturnType<
typeof vi.fn<(sessionId: string, directory: string) => void>
>;
- let spawn: ReturnType<typeof vi.fn>;
let ctx: OpenpodContext;
let baseCtx: OpenpodContext;
+ const execMock = vi.mocked(exec);
beforeAll(async () => {
+ execMock.mockResolvedValue({
+ status: 0,
+ stdout: "",
+ stderr: "",
+ });
baseCtx = await init();
});
beforeEach(() => {
vi.clearAllMocks();
- spawn = spawnSync as unknown as ReturnType<typeof vi.fn>;
- spawn.mockReturnValue({
+ execMock.mockReset();
+ execMock.mockResolvedValue({
status: 0,
+ stdout: "",
+ stderr: "",
});
const tempRoot = path.join(
@@ -66,9 +69,9 @@ describe("handle", () => {
}
});
- it("returns a handle function that can be called", () => {
+ it("returns a handle function that can be called", async () => {
// just ensure no throw on basic call
- handle({
+ await handle({
ctx,
sessionId: "test",
dir: "/tmp/some",
@@ -76,10 +79,10 @@ describe("handle", () => {
});
});
- it("returns early if not git enabled", () => {
- spawn.mockReturnValue({ status: 1 });
+ it("returns early if not git enabled", async () => {
+ execMock.mockResolvedValue({ status: 1, stdout: "", stderr: "" });
- handle({
+ await handle({
ctx,
sessionId: "sess1",
dir: "/project/dir",
@@ -87,184 +90,182 @@ describe("handle", () => {
});
expect(mockMove).not.toHaveBeenCalled();
- expect(spawnSync).toHaveBeenCalledWith(
- "git",
- ["-C", "/project/dir", "rev-parse", "--is-inside-work-tree"],
- { stdio: "ignore" },
- );
+ expect(execMock).toHaveBeenCalledWith("git", [
+ "-C",
+ "/project/dir",
+ "rev-parse",
+ "--is-inside-work-tree",
+ ]);
});
- it("returns early for invalid git (no origin)", () => {
- spawn
- .mockReturnValueOnce({ status: 0 }) // isGitEnabled
- .mockReturnValueOnce({ status: 1, stdout: "" }); // getOriginUrl
+ it("returns early for invalid git (no origin)", async () => {
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // isGitEnabled
+ .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }); // getOriginUrl
const dir = "/project/dir";
- handle({ ctx, sessionId: "sess1", dir, move: mockMove });
+ await handle({ ctx, sessionId: "sess1", dir, move: mockMove });
expect(mockMove).not.toHaveBeenCalled();
- expect(spawnSync).toHaveBeenCalledWith(
+ expect(execMock).toHaveBeenCalledWith(
"git",
["-C", dir, "remote", "get-url", "origin"],
- {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- },
+ { encoding: "utf8" },
);
});
- it("clones project and moves when needs move and target does not exist", () => {
+ it("clones project and moves when needs move and target does not exist", async () => {
const sessionId = "clone-sess";
const dir = "/real/project";
const target = path.join(ctx.openpodRoot, sessionId);
const origin = "https://example.com/repo.git";
- spawn
- .mockReturnValueOnce({ status: 0 }) // isGit
- .mockReturnValueOnce({ status: 0, stdout: origin + "\n" }) // getOrigin
- .mockReturnValueOnce({ status: 0 }) // clone git
- .mockReturnValueOnce({ status: 1 }) // lima list (not exists)
- .mockReturnValueOnce({ status: 0 }) // create lima
- .mockReturnValueOnce({ status: 0 }); // start lima
-
- handle({ ctx, sessionId, dir, move: mockMove });
-
- expect(spawnSync).toHaveBeenCalledWith("git", ["clone", origin, target]);
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // isGit
+ .mockResolvedValueOnce({
+ status: 0,
+ stdout: origin + "\n",
+ stderr: "",
+ }) // getOrigin
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // clone git
+ .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }) // lima list (not exists)
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // create lima
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }); // start lima
+
+ await handle({ ctx, sessionId, dir, move: mockMove });
+
+ expect(execMock).toHaveBeenCalledWith("git", ["clone", origin, target]);
expect(mockMove).toHaveBeenCalledWith(sessionId, target);
// lima create called
- expect(spawnSync).toHaveBeenCalledWith(
- "limactl",
- [
- "create",
- `--name=${sessionId}`,
- `--mount-only=${target}:w`,
- "template:default",
- "--yes",
- ],
- { stdio: "ignore" },
- );
+ expect(execMock).toHaveBeenCalledWith("limactl", [
+ "create",
+ `--name=${sessionId}`,
+ `--mount-only=${target}:w`,
+ "template:default",
+ "--yes",
+ ]);
// start
- expect(spawnSync).toHaveBeenCalledWith(
- "limactl",
- ["start", sessionId, "--yes"],
- { stdio: "ignore" },
- );
+ expect(execMock).toHaveBeenCalledWith("limactl", [
+ "start",
+ sessionId,
+ "--yes",
+ ]);
});
- it("moves session when target already exists (no clone)", () => {
+ it("moves session when target already exists (no clone)", async () => {
const sessionId = "existing";
const dir = "/other/location";
const target = path.join(ctx.openpodRoot, sessionId);
fs.mkdirSync(target, { recursive: true });
- spawn
- .mockReturnValueOnce({ status: 0 }) // is git
- .mockReturnValueOnce({ status: 1 }) // lima not
- .mockReturnValueOnce({ status: 0 }) // create
- .mockReturnValueOnce({ status: 0 }); // start
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // is git
+ .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }) // lima not
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // create
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }); // start
- handle({ ctx, sessionId, dir, move: mockMove });
+ await handle({ ctx, sessionId, dir, move: mockMove });
expect(mockMove).toHaveBeenCalledWith(sessionId, target);
- expect(spawnSync).not.toHaveBeenCalledWith("git", [
+ expect(execMock).not.toHaveBeenCalledWith("git", [
"clone",
expect.anything(),
expect.anything(),
]);
});
- it("does not move when already at target dir", () => {
+ it("does not move when already at target dir", async () => {
const sessionId = "same";
const target = path.join(ctx.openpodRoot, sessionId);
fs.mkdirSync(target, { recursive: true });
- spawn
- .mockReturnValueOnce({ status: 0 }) // git
- .mockReturnValueOnce({ status: 1 }) // lima not exist
- .mockReturnValueOnce({ status: 0 })
- .mockReturnValueOnce({ status: 0 });
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // git
+ .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }) // lima not exist
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" })
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" });
- handle({ ctx, sessionId, dir: target, move: mockMove });
+ await handle({ ctx, sessionId, dir: target, move: mockMove });
expect(mockMove).not.toHaveBeenCalled();
});
- it("skips create if lima instance already exists", () => {
+ it("skips create if lima instance already exists", async () => {
const sessionId = "has-lima";
const dir = path.join(ctx.openpodRoot, sessionId);
fs.mkdirSync(dir, { recursive: true });
- spawn
- .mockReturnValueOnce({ status: 0 }) // git
- .mockReturnValueOnce({ status: 0 }) // lima exists (list status 0)
- .mockReturnValueOnce({ status: 0 }); // start only
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // git
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // lima exists
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }); // start only
- handle({ ctx, sessionId, dir, move: mockMove });
+ await handle({ ctx, sessionId, dir, move: mockMove });
- expect(spawnSync).not.toHaveBeenCalledWith(
+ expect(execMock).not.toHaveBeenCalledWith(
"limactl",
expect.arrayContaining(["create"]),
);
- expect(spawnSync).toHaveBeenCalledWith(
- "limactl",
- ["start", sessionId, "--yes"],
- { stdio: "ignore" },
- );
+ expect(execMock).toHaveBeenCalledWith("limactl", [
+ "start",
+ sessionId,
+ "--yes",
+ ]);
});
- it("handles lima create failure but continues to start", () => {
+ it("handles lima create failure but continues to start", async () => {
const sessionId = "fail-create";
const dir = "/proj";
- spawn
- .mockReturnValueOnce({ status: 0 }) // git
- .mockReturnValueOnce({ status: 0, stdout: "url\n" }) // origin
- .mockReturnValueOnce({ status: 0 }) // clone
- .mockReturnValueOnce({ status: 1 }) // lima not
- .mockReturnValueOnce({ status: 42 }) // create fails
- .mockReturnValueOnce({ status: 0 }); // start succeeds
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // git
+ .mockResolvedValueOnce({ status: 0, stdout: "url\n", stderr: "" }) // origin
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // clone
+ .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }) // lima not
+ .mockResolvedValueOnce({ status: 42, stdout: "", stderr: "" }) // create fails
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }); // start succeeds
- handle({ ctx, sessionId, dir, move: mockMove });
+ await handle({ ctx, sessionId, dir, move: mockMove });
- expect(spawnSync).toHaveBeenCalledWith(
- "limactl",
- ["start", sessionId, "--yes"],
- { stdio: "ignore" },
- );
+ expect(execMock).toHaveBeenCalledWith("limactl", [
+ "start",
+ sessionId,
+ "--yes",
+ ]);
});
- it("handles lima start failure (does not throw)", () => {
+ it("handles lima start failure (does not throw)", async () => {
const sessionId = "fail-start";
const dir = path.join(ctx.openpodRoot, sessionId);
fs.mkdirSync(dir, { recursive: true });
- spawn
- .mockReturnValueOnce({ status: 0 }) // git
- .mockReturnValueOnce({ status: 0 }) // lima exists
- .mockReturnValueOnce({ status: 1 }); // start fails
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // git
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // lima exists
+ .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }); // start fails
- handle({ ctx, sessionId, dir, move: mockMove });
+ await handle({ ctx, sessionId, dir, move: mockMove });
});
- it("handles git clone failure and does not move", () => {
+ it("handles git clone failure and does not move", async () => {
const sessionId = "clone-fail";
const dir = "/proj";
const origin = "https://bad";
- spawn
- .mockReturnValueOnce({ status: 0 }) // git
- .mockReturnValueOnce({ status: 0, stdout: origin + "\n" })
- .mockReturnValueOnce({ status: 1 }); // clone fails -- no more calls
+ execMock
+ .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) // git
+ .mockResolvedValueOnce({
+ status: 0,
+ stdout: origin + "\n",
+ stderr: "",
+ })
+ .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }); // clone fails
- handle({ ctx, sessionId, dir, move: mockMove });
+ await handle({ ctx, sessionId, dir, move: mockMove });
expect(mockMove).not.toHaveBeenCalled();
// no lima/start since returned early
- expect(spawnSync).not.toHaveBeenCalledWith(
- expect.stringContaining("limactl"),
- expect.any(Array),
- expect.any(Object),
- );
+ expect(execMock).not.toHaveBeenCalledWith("limactl", expect.any(Array));
});
});
diff --git a/prompt/handle.ts b/prompt/handle.ts
@@ -1,8 +1,10 @@
import type { OpenpodContext } from "../context";
-import { spawnSync } from "node:child_process";
-import * as fs from "node:fs";
+import { mkdir, rm } from "node:fs/promises";
import * as path from "node:path";
+import { exec } from "../context/exec";
+import { exists } from "../context/fs";
+
export type HandleParams = {
ctx: OpenpodContext;
sessionId: string;
@@ -10,92 +12,76 @@ export type HandleParams = {
move: (sessionId: string, directory: string) => void;
};
-export function handle(params: HandleParams): void {
+export async function handle(params: HandleParams): Promise<void> {
const { ctx: deps, sessionId, dir, move } = params;
const { logger, openpodRoot } = deps;
- function isGitEnabled(dir: string): boolean {
- try {
- const result = spawnSync(
- "git",
- ["-C", dir, "rev-parse", "--is-inside-work-tree"],
- {
- stdio: "ignore",
- },
- );
- return result.status === 0;
- } catch {
- return false;
- }
+ async function isGitEnabled(dir: string): Promise<boolean> {
+ const result = await exec("git", [
+ "-C",
+ dir,
+ "rev-parse",
+ "--is-inside-work-tree",
+ ]);
+ return result.status === 0;
}
- function getOriginUrl(dir: string): string | null {
- try {
- const result = spawnSync(
- "git",
- ["-C", dir, "remote", "get-url", "origin"],
- {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- },
- );
- if (result.status !== 0 || !result.stdout?.trim()) {
- return null;
- }
- return result.stdout.trim();
- } catch {
+ async function getOriginUrl(dir: string): Promise<string | null> {
+ const result = await exec(
+ "git",
+ ["-C", dir, "remote", "get-url", "origin"],
+ {
+ encoding: "utf8",
+ },
+ );
+ if (result.status !== 0 || !result.stdout.trim()) {
return null;
}
+ return result.stdout.trim();
}
- function limaInstanceExists(name: string): boolean {
- try {
- const result = spawnSync("limactl", ["list", name], {
- stdio: "ignore",
- });
- return result.status === 0;
- } catch {
- return false;
- }
+ async function limaInstanceExists(name: string): Promise<boolean> {
+ const result = await exec("limactl", ["list", name]);
+ return result.status === 0;
}
- function createLimaInstance(sessionId: string, target: string): void {
- logger.log(`creating lima instance ${sessionId} (mount-only ${target}:w)`);
- const createResult = spawnSync(
- "limactl",
- [
- "create",
- `--name=${sessionId}`,
- `--mount-only=${target}:w`,
- "template:default",
- "--yes",
- ],
- {
- stdio: "ignore",
- },
+ async function createLimaInstance(
+ sessionId: string,
+ target: string,
+ ): Promise<void> {
+ await logger.log(
+ `creating lima instance ${sessionId} (mount-only ${target}:w)`,
);
+ const createResult = await exec("limactl", [
+ "create",
+ `--name=${sessionId}`,
+ `--mount-only=${target}:w`,
+ "template:default",
+ "--yes",
+ ]);
if (createResult.status !== 0) {
- logger.log(`limactl create exited with ${createResult.status}`);
+ await logger.log(`limactl create exited with ${createResult.status}`);
}
}
- function startLimaInstance(sessionId: string): void {
- logger.log(`starting lima instance ${sessionId}`);
- const startResult = spawnSync("limactl", ["start", sessionId, "--yes"], {
- stdio: "ignore",
- });
+ async function startLimaInstance(sessionId: string): Promise<void> {
+ await logger.log(`starting lima instance ${sessionId}`);
+ const startResult = await exec("limactl", ["start", sessionId, "--yes"]);
if (startResult.status !== 0) {
- logger.log(`limactl start exited with ${startResult.status}`);
+ await logger.log(`limactl start exited with ${startResult.status}`);
}
}
- function cloneProject(originUrl: string, target: string): boolean {
- fs.mkdirSync(openpodRoot, { recursive: true });
- const result = spawnSync("git", ["clone", originUrl, target]);
+ async function cloneProject(
+ originUrl: string,
+ target: string,
+ ): Promise<boolean> {
+ await mkdir(openpodRoot, { recursive: true });
+ const result = await exec("git", ["clone", originUrl, target]);
if (result.status !== 0) {
- logger.log(`git clone failed with exit code ${result.status}`);
+ await logger.log(`git clone failed with exit code ${result.status}`);
try {
- fs.rmSync(target, { recursive: true, force: true });
+ await rm(target, { recursive: true, force: true });
} catch {
// ignore cleanup failure
}
@@ -104,47 +90,47 @@ export function handle(params: HandleParams): void {
return true;
}
- const gitEnabled = isGitEnabled(dir);
- logger.log(`session ${sessionId} prompt - gitEnabled: ${gitEnabled}`);
+ const gitEnabled = await isGitEnabled(dir);
+ await logger.log(`session ${sessionId} prompt - gitEnabled: ${gitEnabled}`);
if (!gitEnabled) {
- logger.log(`git is not enabled`);
+ await logger.log(`git is not enabled`);
return;
}
const target = path.join(openpodRoot, sessionId);
const needsMove = dir !== target;
- logger.log(
+ await logger.log(
`needs move for project dir ${dir}? ${needsMove} (target=${target})`,
);
if (needsMove) {
- if (fs.existsSync(target)) {
- logger.log(`${target} already exists`);
+ if (await exists(target)) {
+ await logger.log(`${target} already exists`);
move(sessionId, target);
} else {
- const originUrl = getOriginUrl(dir);
+ const originUrl = await getOriginUrl(dir);
if (!originUrl) {
- logger.log(`no origin remote configured`);
+ await logger.log(`no origin remote configured`);
return;
}
- logger.log(`cloning from origin ${originUrl} -> ${target}`);
- if (!cloneProject(originUrl, target)) {
+ await logger.log(`cloning from origin ${originUrl} -> ${target}`);
+ if (!(await cloneProject(originUrl, target))) {
return;
}
- logger.log(`clone complete, moving session to ${target}`);
+ await logger.log(`clone complete, moving session to ${target}`);
move(sessionId, target);
}
} else {
- logger.log(`already in ${target} directory`);
+ await logger.log(`already in ${target} directory`);
}
- if (!limaInstanceExists(sessionId)) {
- createLimaInstance(sessionId, target);
+ if (!(await limaInstanceExists(sessionId))) {
+ await createLimaInstance(sessionId, target);
}
- startLimaInstance(sessionId);
+ await startLimaInstance(sessionId);
}
diff --git a/prompt/index.ts b/prompt/index.ts
@@ -10,7 +10,7 @@ export async function registerPrompt(
): Promise<void> {
const { logger } = deps;
- logger.log("registering prompt");
+ await logger.log("registering prompt");
await ctx.session.hook("prompt", async (event) => {
const session = await ctx.session.get({ sessionID: event.sessionID });
@@ -25,6 +25,6 @@ export async function registerPrompt(
},
};
- handle(params);
+ await handle(params);
});
}
diff --git a/shell/index.ts b/shell/index.ts
@@ -10,9 +10,9 @@ export async function registerShell(
): Promise<void> {
const { logger } = deps;
- logger.log("registering create.before");
+ await logger.log("registering create.before");
await ctx.shell.hook("create.before", async (event) => {
- event.command = wrap(deps, event.cwd, event.command);
+ event.command = await wrap(deps, event.cwd, event.command);
});
}
diff --git a/shell/wrap.test.ts b/shell/wrap.test.ts
@@ -12,45 +12,45 @@ describe("wrap", () => {
ctx = await init();
});
- it("returns original command when cwd is outside openpodRoot", () => {
+ it("returns original command when cwd is outside openpodRoot", async () => {
const command = "echo hello";
- const result = wrap(ctx, "/tmp/some/random/dir", command);
+ const result = await wrap(ctx, "/tmp/some/random/dir", command);
expect(result).toBe(command);
});
- it("returns original command when cwd is exactly openpodRoot", () => {
+ it("returns original command when cwd is exactly openpodRoot", async () => {
const command = "ls";
- const result = wrap(ctx, ctx.openpodRoot, command);
+ const result = await wrap(ctx, ctx.openpodRoot, command);
expect(result).toBe(command);
});
- it("wraps command using first directory segment as lima name", () => {
+ it("wraps command using first directory segment as lima name", async () => {
const session = "my-session-abc";
const cwd = path.join(ctx.openpodRoot, session);
const command = "npm run dev";
- const result = wrap(ctx, cwd, command);
+ const result = await wrap(ctx, cwd, command);
expect(result).toBe(
`limactl shell --preserve-env --workdir='${cwd}' ${session} bash -c '${command}'`,
);
});
- it("uses only the first segment even for nested directories", () => {
+ it("uses only the first segment even for nested directories", async () => {
const session = "sess-xyz";
const cwd = path.join(ctx.openpodRoot, session, "src", "app");
const command = "cat package.json";
- const result = wrap(ctx, cwd, command);
+ const result = await wrap(ctx, cwd, command);
expect(result).toBe(
`limactl shell --preserve-env --workdir='${cwd}' ${session} bash -c '${command}'`,
);
});
- it("escapes single quotes in cwd and command", () => {
+ it("escapes single quotes in cwd and command", async () => {
const session = "sess'with'quotes";
const cwd = path.join(ctx.openpodRoot, session, "sub'dir");
const command = "echo 'hello world'";
- const result = wrap(ctx, cwd, command);
+ const result = await wrap(ctx, cwd, command);
const escapedCwd = cwd.replace(/'/g, "'\\''");
const escapedCmd = command.replace(/'/g, "'\\''");
@@ -59,10 +59,10 @@ describe("wrap", () => {
expect(result).toBe(expected);
});
- it("returns original command for paths that would escape the tree", () => {
+ it("returns original command for paths that would escape the tree", async () => {
const command = "pwd";
const outside = path.join(ctx.openpodRoot, "..", "escape");
- const result = wrap(ctx, outside, command);
+ const result = await wrap(ctx, outside, command);
expect(result).toBe(command);
});
});
diff --git a/shell/wrap.ts b/shell/wrap.ts
@@ -1,15 +1,15 @@
import type { OpenpodContext } from "../context";
import * as path from "node:path";
-export function wrap(
+export async function wrap(
deps: OpenpodContext,
cwd: string,
command: string,
-): string {
- function getLimaName(dir: string): string | null {
+): Promise<string> {
+ async function getLimaName(dir: string): Promise<string | null> {
const { logger, openpodRoot } = deps;
try {
- logger.log(`get lima name for ${openpodRoot} ${dir}`);
+ await logger.log(`get lima name for ${openpodRoot} ${dir}`);
const rel = path.relative(openpodRoot, dir);
if (rel.startsWith("..") || path.isAbsolute(rel)) {
return null;
@@ -21,7 +21,7 @@ export function wrap(
}
}
- const limaName = getLimaName(cwd);
+ const limaName = await getLimaName(cwd);
if (!limaName) {
return command;
}
@@ -30,7 +30,9 @@ export function wrap(
const escapedCmd = command.replace(/'/g, "'\\''");
const wrapped = `limactl shell --preserve-env --workdir='${escapedCwd}' ${limaName} bash -c '${escapedCmd}'`;
- deps.logger.log(`redirected shell command for lima ${limaName} (cwd=${cwd})`);
+ await deps.logger.log(
+ `redirected shell command for lima ${limaName} (cwd=${cwd})`,
+ );
return wrapped;
}