src / root.ts
import { promises as fs } from "fs";
import * as os from "os";
import * as path from "path";
const NO_DIR_MESSAGE =
'read-write: no working directory. Set "Working directory" in the plugin settings, or attach one to the chat.';
/**
* Decide the scope root. A non-empty setting wins and must be valid (no silent
* fallback); otherwise the chat's working directory is used.
*/
export async function resolveRoot(
configured: string,
getChatDir: () => string,
homedir: () => string = os.homedir,
): Promise<string> {
const entered = configured.trim();
if (entered === "") {
try {
return getChatDir();
} catch {
throw new Error(NO_DIR_MESSAGE);
}
}
const invalid = () =>
new Error(
`read-write: "Working directory" setting must be an absolute path to an existing directory (got: ${configured})`,
);
let candidate = entered;
if (candidate === "~") candidate = homedir();
else if (candidate.startsWith("~/")) candidate = path.join(homedir(), candidate.slice(2));
if (!path.isAbsolute(candidate)) throw invalid();
try {
const real = await fs.realpath(candidate);
if (!(await fs.stat(real)).isDirectory()) throw invalid();
return real;
} catch {
throw invalid();
}
}
src / root.ts
import { promises as fs } from "fs";
import * as os from "os";
import * as path from "path";
const NO_DIR_MESSAGE =
'read-write: no working directory. Set "Working directory" in the plugin settings, or attach one to the chat.';
/**
* Decide the scope root. A non-empty setting wins and must be valid (no silent
* fallback); otherwise the chat's working directory is used.
*/
export async function resolveRoot(
configured: string,
getChatDir: () => string,
homedir: () => string = os.homedir,
): Promise<string> {
const entered = configured.trim();
if (entered === "") {
try {
return getChatDir();
} catch {
throw new Error(NO_DIR_MESSAGE);
}
}
const invalid = () =>
new Error(
`read-write: "Working directory" setting must be an absolute path to an existing directory (got: ${configured})`,
);
let candidate = entered;
if (candidate === "~") candidate = homedir();
else if (candidate.startsWith("~/")) candidate = path.join(homedir(), candidate.slice(2));
if (!path.isAbsolute(candidate)) throw invalid();
try {
const real = await fs.realpath(candidate);
if (!(await fs.stat(real)).isDirectory()) throw invalid();
return real;
} catch {
throw invalid();
}
}