1import path from 'path'; 2import resolveFrom from 'resolve-from'; 3 4import { CommandError } from '../utils/errors'; 5 6/** Look up directories until one with a `package.json` can be found, assert if none can be found. */ 7export function findUpProjectRootOrAssert(cwd: string): string { 8 const projectRoot = findUpProjectRoot(cwd); 9 if (!projectRoot) { 10 throw new CommandError(`Project root directory not found (working directory: ${cwd})`); 11 } 12 return projectRoot; 13} 14 15function findUpProjectRoot(cwd: string): string | null { 16 if (['.', path.sep].includes(cwd)) return null; 17 18 const found = resolveFrom.silent(cwd, './package.json'); 19 if (found) { 20 return path.dirname(found); 21 } 22 return findUpProjectRoot(path.dirname(cwd)); 23} 24