UNPKG

@mountainpass/hooked-cli

Version:
39 lines (38 loc) 1.37 kB
import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { isString } from '../types.js'; import logger from './logger.js'; export const findFileInAncestors = (dirname, filename, throwError = true) => { // find filename let i = 0; let filepath; const maxDepth = 10; for (; i < maxDepth; i++) { const tmp = path.resolve(dirname, '../'.repeat(i), filename); if (fs.existsSync(tmp)) { logger.debug(`Found '${filename}' at ${tmp}, ${i} folder/s up from ${dirname}.`); filepath = tmp; break; } } if (!isString(filepath)) { if (throwError) { throw new Error(`Could not find '${filename}' in parent directories! baseDir=${dirname}`); } else { logger.error(`Could not find '${filename}' in parent directories! baseDir=${dirname}`); return dirname; } } return filepath; }; // all this just to load a json file... sigh ESM export const loadRootPackageJsonSync = () => { const dirname = path.dirname(fileURLToPath(import.meta.url)); const filepath = findFileInAncestors(dirname, 'package.json', true); return loadPackageJsonSync(filepath); }; export const loadPackageJsonSync = (packageJsonPath) => { return JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); };