49 lines
2.2 KiB
TypeScript
49 lines
2.2 KiB
TypeScript
// PEP-241: Codex asks «Trust this folder?» for a folder it does not know and waits for a key. It looks
|
|
// the trust up by the git project root — for a worktree that is the root of the main repository, not
|
|
// the worktree folder. And its `-c a.b.c=…` override splits the key on every dot, quoted or not, so a
|
|
// path with a dot (`~/.peppa/…`) never matches through `-c`: the subscription's config.toml does.
|
|
import { appendFileSync, existsSync, readFileSync, statSync } from "node:fs";
|
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
|
|
/** The folders Codex may ask about for `cwd`: the folder itself and, for a worktree, the main repository's root. */
|
|
export function codexTrustRoots(cwd: string): string[] {
|
|
const roots = [cwd];
|
|
try {
|
|
const dotGit = join(cwd, ".git");
|
|
if (existsSync(dotGit) && statSync(dotGit).isFile()) {
|
|
const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
|
|
if (m) {
|
|
const gitdir = resolve(cwd, m[1]!.trim());
|
|
const commonFile = join(gitdir, "commondir");
|
|
const common = existsSync(commonFile) ? resolve(gitdir, readFileSync(commonFile, "utf8").trim()) : resolve(gitdir, "../..");
|
|
const root = basename(common) === ".git" ? dirname(common) : common;
|
|
if (!roots.includes(root)) roots.push(root);
|
|
}
|
|
}
|
|
} catch {
|
|
/* not a git folder — the folder itself is enough */
|
|
}
|
|
return roots;
|
|
}
|
|
|
|
/**
|
|
* Marks the folders trusted in `<codexHome>/config.toml`. A folder already named in the file is left
|
|
* alone: a second `[projects."…"]` table would make the whole config unreadable for Codex.
|
|
*/
|
|
export function trustCodexFolders(codexHome: string, folders: string[]): string[] {
|
|
const file = join(codexHome, "config.toml");
|
|
const text = existsSync(file) ? readFileSync(file, "utf8") : "";
|
|
const added: string[] = [];
|
|
for (const f of folders) {
|
|
if (!isAbsolute(f)) continue;
|
|
const key = JSON.stringify(f);
|
|
if (text.includes(key)) continue;
|
|
added.push(f);
|
|
}
|
|
if (added.length) {
|
|
const block = added.map((f) => `[projects.${JSON.stringify(f)}]\ntrust_level = "trusted"\n`).join("\n");
|
|
appendFileSync(file, `${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}${block}`, { mode: 0o600 });
|
|
}
|
|
return added;
|
|
}
|