import { readdirSync, statSync, realpathSync } from "node:fs"; import { delimiter } from "node:path"; export type IndexedCommand = { name: string; resolvedPath: string; }; export type CommandIndex = { commands: IndexedCommand[]; names: string[]; }; export function scanCurrentPath(): CommandIndex { const rawPath = process.env.PATH; if (!rawPath) { throw new Error("PATH is not set"); } return scanPathEntries(rawPath.split(delimiter)); } export function scanPathEntries(entries: string[]): CommandIndex { const commands: IndexedCommand[] = []; const seen = new Set(); for (const directory of entries) { if (!directory) { continue; } let dirEntries; try { dirEntries = readdirSync(directory, { withFileTypes: true }); } catch (error) { const message = error instanceof Error ? error.message : "unknown failure"; if (message.includes("no such file")) { continue; } throw new Error(`failed to read PATH directory ${directory}: ${message}`); } for (const entry of dirEntries) { const name = entry.name; if (seen.has(name)) { continue; } const resolvedPath = resolveInvokableCommand(`${directory}/${name}`); if (!resolvedPath) { continue; } seen.add(name); commands.push({ name, resolvedPath }); } } return { commands, names: commands.map((command) => command.name) }; } function resolveInvokableCommand(path: string): string | null { try { const resolvedPath = realpathSync(path); const metadata = statSync(resolvedPath); if (!metadata.isFile() || (metadata.mode & 0o111) === 0) { return null; } return resolvedPath; } catch { return null; } }