repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/the-system/project-root.ts
RawFile outline
import { existsSync } from "node:fs";
import path from "node:path";
export class SystemDocumentError extends Error {
readonly code: string;
constructor(code: string, message: string) {
super(message);
this.code = code;
this.name = "SystemDocumentError";
}
}
const nearestMarker = (
cwd: string,
marker: string,
markerExists: (candidate: string) => boolean,
) => {
let current = path.resolve(cwd);
while (true) {
if (markerExists(path.join(current, marker))) return current;
const parent = path.dirname(current);
if (parent === current) return undefined;
current = parent;
}
};
export function discoverProjectRoot(
cwd: string,
markerExists = existsSync,
): string {
const resolvedCwd = path.resolve(cwd);
const jj = nearestMarker(resolvedCwd, ".jj", markerExists);
const git = nearestMarker(resolvedCwd, ".git", markerExists);
if (jj && git && jj !== git)
throw new SystemDocumentError(
"root.conflict",
`Conflicting project roots: Git ${git}; JJ ${jj}`,
);
return jj ?? git ?? resolvedCwd;
}