Skip to content

Commit

Permalink
Merge pull request #164 from Automattic/fix/package-json-iterator-take-2
Browse files Browse the repository at this point in the history
Improve tree traversal to find package root
  • Loading branch information
chriszarate authored Jun 7, 2023
2 parents b6a8d6f + f8c5a18 commit ab5b6e2
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion utils/is-package-installed.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
const debugLog = require( './debug-log' );
const findPackageJson = require( 'find-package-json' );

const parent = findPackageJson( __dirname ).next()?.value || {};
// Get a list of all package.json files in the current directory tree, ascending
// up the tree from the current directory. Note that this code behaves differently
// when it is installed as a package vs. when we are linting the code in this repo.
//
// When installed as a package, the current directory is inside node_modules and is
// not the "package root" as we are thinking about it. In this case, we need to ignore
// all package.json files that are inside node_modules directories.
//
// When we are linting the code in this repo, the current directory is not inside
// node_modules and the first found "package.json" is the "package root."
//
// This problem is basically impossible to solve for all edge cases (like someone who
// runs `npm run lint` from inside "node_modules") but this code should work for
// most cases.
const packages = [ ...findPackageJson( __dirname ) ];
const parent =
packages.find( pkg => ! pkg.__path.includes( '/node_modules/' ) ) || packages.pop() || {};

debugLog( `Found package.json: ${ parent.__path || 'none' }` );

Expand Down

0 comments on commit ab5b6e2

Please sign in to comment.