import { constants } from "node:fs"; import { access, mkdir, readFile, realpath, stat, writeFile, } from "node:fs/promises"; import path from "node:path"; import { parse, stringify } from "yaml"; import { stringifyMarkdownFrontmatter } from "./frontmatter.js"; import { DEFAULT_PROJECT_LANGUAGE, type PonyConfig, createDefaultConfig, normalizeConfig, } from "./schemas.js"; export const PONY_DIR = ".pony"; export const CONFIG_FILE = "config.yml"; export const INSTRUCTIONS_FILE = "instructions.md"; export interface PonyProject { root: string; ponyDir: string; configPath: string; config: PonyConfig; } export interface InitProjectResult { project: PonyProject; createdConfig: boolean; } export function getWorkspaceCwd(cwd = process.cwd()): string { return process.env.PONY_WORKSPACE_CWD ?? cwd; } export async function pathExists(targetPath: string): Promise { try { await access(targetPath, constants.F_OK); return true; } catch { return false; } } export async function findProjectRoot( startCwd = getWorkspaceCwd(), ): Promise { let current = path.resolve(startCwd); while (true) { if (await pathExists(path.join(current, PONY_DIR, CONFIG_FILE))) { return current; } const parent = path.dirname(current); if (parent === current) { return null; } current = parent; } } export async function readConfig(root: string): Promise { const configPath = path.join(root, PONY_DIR, CONFIG_FILE); const raw = await readFile(configPath, "utf8"); return normalizeConfig(parse(raw), path.basename(root)); } export async function requireProject( cwd = getWorkspaceCwd(), ): Promise { const root = await findProjectRoot(cwd); if (!root) { throw new Error("No .pony/config.yml found. Run `pony init` first."); } const ponyDir = path.join(root, PONY_DIR); return { root, ponyDir, configPath: path.join(ponyDir, CONFIG_FILE), config: await readConfig(root), }; } async function canonicalPonyDirectory( input: string, cwd: string, ): Promise { const resolvedPath = path.resolve(cwd, input); try { const details = await stat(resolvedPath); if (!details.isDirectory()) { throw new Error("the path is not a directory"); } const ponyDirectory = path.basename(resolvedPath) === PONY_DIR ? resolvedPath : path.join(resolvedPath, PONY_DIR); const ponyDetails = await stat(ponyDirectory); if (!ponyDetails.isDirectory()) { throw new Error(`${ponyDirectory} is not a directory`); } const canonicalDirectory = await realpath(ponyDirectory); await access(path.join(canonicalDirectory, CONFIG_FILE), constants.R_OK); return canonicalDirectory; } catch (error) { const reason = error instanceof Error ? error.message : String(error); throw new Error( `Could not load Pony project path "${input}": ${reason}. Select an accessible project root or .pony directory containing config.yml.`, ); } } async function requireExplicitProject( input: string, canonicalDirectory: string, ): Promise { try { return await requireProject(path.dirname(canonicalDirectory)); } catch (error) { const reason = error instanceof Error ? error.message : String(error); throw new Error(`Could not load Pony directory "${input}": ${reason}`); } } /** * Explicit multi-project startup accepts project roots or their `.pony` * directories without searching parent directories. This prevents a typo from * silently resolving to a different repository higher in the filesystem. */ export async function requireProjectsFromPaths( projectPaths: string[], cwd = getWorkspaceCwd(), ): Promise { const projects: PonyProject[] = []; const seenDirectories = new Map(); for (const input of projectPaths) { const canonicalDirectory = await canonicalPonyDirectory(input, cwd); const duplicateOf = seenDirectories.get(canonicalDirectory); if (duplicateOf) { throw new Error( `Duplicate Pony directory "${input}" resolves to the same project as "${duplicateOf}". Remove one of the duplicate paths.`, ); } seenDirectories.set(canonicalDirectory, input); projects.push(await requireExplicitProject(input, canonicalDirectory)); } if (projects.length === 0) { throw new Error("Select at least one Pony project path."); } return projects; } export async function initProject( cwd = getWorkspaceCwd(), projectName = path.basename(path.resolve(cwd)), projectLanguage = DEFAULT_PROJECT_LANGUAGE, ): Promise { const root = path.resolve(cwd); const ponyDir = path.join(root, PONY_DIR); const configPath = path.join(ponyDir, CONFIG_FILE); const createdConfig = !(await pathExists(configPath)); const newConfig = createdConfig ? createDefaultConfig(projectName, projectLanguage) : null; await mkdir(path.join(ponyDir, "inbox"), { recursive: true }); await mkdir(path.join(ponyDir, "tasks"), { recursive: true }); await mkdir(path.join(ponyDir, "docs"), { recursive: true }); if (newConfig) { await writeFile( configPath, stringify(newConfig, { lineWidth: 0, }), "utf8", ); const instructionsPath = path.join(ponyDir, INSTRUCTIONS_FILE); if (!(await pathExists(instructionsPath))) { await writeFile( instructionsPath, `${stringifyMarkdownFrontmatter("", { type: "instructions", }).trimEnd()}\n`, "utf8", ); } } return { project: { root, ponyDir, configPath, config: await readConfig(root), }, createdConfig, }; } export function projectRelativePath( project: PonyProject, absolutePath: string, ): string { return path .relative(project.root, absolutePath) .split(path.sep) .join(path.posix.sep); }