Skip to content

Commit

Permalink
[Refactor] no-extraneous-dependencies improve performance using cache
Browse files Browse the repository at this point in the history
  • Loading branch information
meowtec committed Jan 27, 2022
1 parent 0d14165 commit 9d7efd5
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/rules/no-extraneous-dependencies.js
@@ -1,6 +1,6 @@
import path from 'path';
import fs from 'fs';
import readPkgUp from 'eslint-module-utils/readPkgUp';
import pkgUp from 'eslint-module-utils/pkgUp';
import minimatch from 'minimatch';
import resolve from 'eslint-module-utils/resolve';
import moduleVisitor from 'eslint-module-utils/moduleVisitor';
Expand Down Expand Up @@ -30,6 +30,17 @@ function extractDepFields(pkg) {
};
}

function getPackageDepFields(packageJsonPath) {
if (!depFieldCache.has(packageJsonPath)) {
const depFields = extractDepFields(
JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')),
);
depFieldCache.set(packageJsonPath, depFields);
}

return depFieldCache.get(packageJsonPath);
}

function getDependencies(context, packageDir) {
let paths = [];
try {
Expand All @@ -53,24 +64,21 @@ function getDependencies(context, packageDir) {
// use rule config to find package.json
paths.forEach(dir => {
const packageJsonPath = path.join(dir, 'package.json');
if (!depFieldCache.has(packageJsonPath)) {
const depFields = extractDepFields(
JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')),
);
depFieldCache.set(packageJsonPath, depFields);
}
const _packageContent = depFieldCache.get(packageJsonPath);
const _packageContent = getPackageDepFields(packageJsonPath);
Object.keys(packageContent).forEach(depsKey =>
Object.assign(packageContent[depsKey], _packageContent[depsKey]),
);
});
} else {
const packageJsonPath = pkgUp({
cwd: context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename(),
normalize: false,
});

// use closest package.json
Object.assign(
packageContent,
extractDepFields(
readPkgUp({ cwd: context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename(), normalize: false }).pkg,
),
getPackageDepFields(packageJsonPath),
);
}

Expand Down

0 comments on commit 9d7efd5

Please sign in to comment.