diff --git a/.changeset/skip-when-no-package-json.md b/.changeset/skip-when-no-package-json.md new file mode 100644 index 0000000..ed7bb0d --- /dev/null +++ b/.changeset/skip-when-no-package-json.md @@ -0,0 +1,5 @@ +--- +"simple-git-hooks": patch +--- + +fix: don't crash `postinstall` when the resolved project directory has no package.json — skip instead of throwing an uncaught ENOENT diff --git a/simple-git-hooks.js b/simple-git-hooks.js index 9ade519..bf673d4 100644 --- a/simple-git-hooks.js +++ b/simple-git-hooks.js @@ -152,6 +152,12 @@ function checkSimpleGitHooksInDependencies(projectRootPath) { throw TypeError("Package json path is not a string!") } + // No package.json means we're not in a project that depends on simple-git-hooks + // (e.g. postinstall resolved to a directory without one) — skip instead of crashing. + if (!fs.existsSync(path.normalize(projectRootPath + '/package.json'))) { + return false + } + const {packageJsonContent} = _getPackageJson(projectRootPath) // if simple-git-hooks in dependencies -> note user that he should remove move it to devDeps! @@ -325,7 +331,7 @@ function _getPackageJson(projectPath = process.cwd()) { const targetPackageJson = path.normalize(projectPath + '/package.json') - if (!fs.statSync(targetPackageJson).isFile()) { + if (!fs.existsSync(targetPackageJson) || !fs.statSync(targetPackageJson).isFile()) { throw Error("Package.json doesn't exist") } diff --git a/simple-git-hooks.test.js b/simple-git-hooks.test.js index 0093217..1bf4ea4 100644 --- a/simple-git-hooks.test.js +++ b/simple-git-hooks.test.js @@ -129,6 +129,20 @@ describe("Simple Git Hooks tests", () => { simpleGitHooks.checkSimpleGitHooksInDependencies(PROJECT_WITHOUT_SIMPLE_GIT_HOOKS) ).toBe(false); }); + + it("returns false (does not throw) when package.json does not exist", () => { + // A directory that exists but has no package.json (the postinstall scenario in #112) + const dirWithoutPackageJson = fs.mkdtempSync( + path.join(process.cwd(), "_tests", "no_package_json_") + ); + try { + expect( + simpleGitHooks.checkSimpleGitHooksInDependencies(dirWithoutPackageJson) + ).toBe(false); + } finally { + fs.rmSync(dirWithoutPackageJson, { recursive: true, force: true }); + } + }); }); });