refactor(test): reuse env helper in temp home harness
This commit is contained in:
@@ -1,39 +1,7 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
type HomeEnvSnapshot = {
|
||||
home: string | undefined;
|
||||
userProfile: string | undefined;
|
||||
homeDrive: string | undefined;
|
||||
homePath: string | undefined;
|
||||
stateDir: string | undefined;
|
||||
};
|
||||
|
||||
function snapshotHomeEnv(): HomeEnvSnapshot {
|
||||
return {
|
||||
home: process.env.HOME,
|
||||
userProfile: process.env.USERPROFILE,
|
||||
homeDrive: process.env.HOMEDRIVE,
|
||||
homePath: process.env.HOMEPATH,
|
||||
stateDir: process.env.OPENCLAW_STATE_DIR,
|
||||
};
|
||||
}
|
||||
|
||||
function restoreHomeEnv(snapshot: HomeEnvSnapshot) {
|
||||
const restoreKey = (key: string, value: string | undefined) => {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
};
|
||||
restoreKey("HOME", snapshot.home);
|
||||
restoreKey("USERPROFILE", snapshot.userProfile);
|
||||
restoreKey("HOMEDRIVE", snapshot.homeDrive);
|
||||
restoreKey("HOMEPATH", snapshot.homePath);
|
||||
restoreKey("OPENCLAW_STATE_DIR", snapshot.stateDir);
|
||||
}
|
||||
import { captureEnv } from "../test-utils/env.js";
|
||||
|
||||
export async function withTempHome<T>(
|
||||
prefix: string,
|
||||
@@ -42,7 +10,13 @@ export async function withTempHome<T>(
|
||||
const home = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
||||
await fs.mkdir(path.join(home, ".openclaw"), { recursive: true });
|
||||
|
||||
const snapshot = snapshotHomeEnv();
|
||||
const snapshot = captureEnv([
|
||||
"HOME",
|
||||
"USERPROFILE",
|
||||
"HOMEDRIVE",
|
||||
"HOMEPATH",
|
||||
"OPENCLAW_STATE_DIR",
|
||||
]);
|
||||
process.env.HOME = home;
|
||||
process.env.USERPROFILE = home;
|
||||
process.env.OPENCLAW_STATE_DIR = path.join(home, ".openclaw");
|
||||
@@ -58,7 +32,7 @@ export async function withTempHome<T>(
|
||||
try {
|
||||
return await fn(home);
|
||||
} finally {
|
||||
restoreHomeEnv(snapshot);
|
||||
snapshot.restore();
|
||||
await fs.rm(home, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user