@baseplate-dev/sync
Version:
Library for syncing Baseplate descriptions
35 lines • 1.44 kB
JavaScript
import { enhanceErrorWithContext } from '@baseplate-dev/utils';
import { findNearestPackageJson } from '@baseplate-dev/utils/node';
import { readFile } from 'node:fs/promises';
/**
* Finds the package name for a generator based on its directory
* Uses a cache to avoid repeated filesystem lookups
*/
export async function findGeneratorPackageName(generatorDirectory, cache) {
const cachedName = cache.get(generatorDirectory);
if (cachedName)
return cachedName;
// Find the nearest package.json
const packageJsonPath = await findNearestPackageJson({
cwd: generatorDirectory,
});
if (!packageJsonPath) {
throw new Error(`No package.json found for generator at ${generatorDirectory}`);
}
try {
// Read and parse the package.json
const packageJsonContent = await readFile(packageJsonPath, 'utf8');
const packageJson = JSON.parse(packageJsonContent);
const packageName = packageJson && typeof packageJson === 'object' && packageJson.name;
if (!packageName) {
throw new Error(`No package name found in ${packageJsonPath}`);
}
// Cache the result
cache.set(generatorDirectory, packageName);
return packageName;
}
catch (error) {
throw enhanceErrorWithContext(error, `Failed to read or parse package.json at ${packageJsonPath}`);
}
}
//# sourceMappingURL=find-generator-package-name.js.map