1
1
import path from 'path' ;
2
2
import fs from 'fs' ;
3
- import readPkgUp from 'eslint-module-utils/readPkgUp ' ;
3
+ import pkgUp from 'eslint-module-utils/pkgUp ' ;
4
4
import minimatch from 'minimatch' ;
5
5
import resolve from 'eslint-module-utils/resolve' ;
6
6
import moduleVisitor from 'eslint-module-utils/moduleVisitor' ;
@@ -18,6 +18,16 @@ function arrayOrKeys(arrayOrObject) {
18
18
return Array . isArray ( arrayOrObject ) ? arrayOrObject : Object . keys ( arrayOrObject ) ;
19
19
}
20
20
21
+ function readJSON ( jsonPath , throwException ) {
22
+ try {
23
+ return JSON . parse ( fs . readFileSync ( jsonPath , 'utf8' ) ) ;
24
+ } catch ( err ) {
25
+ if ( throwException ) {
26
+ throw err ;
27
+ }
28
+ }
29
+ }
30
+
21
31
function extractDepFields ( pkg ) {
22
32
return {
23
33
dependencies : pkg . dependencies || { } ,
@@ -30,6 +40,15 @@ function extractDepFields(pkg) {
30
40
} ;
31
41
}
32
42
43
+ function getPackageDepFields ( packageJsonPath , throwAtRead ) {
44
+ if ( ! depFieldCache . has ( packageJsonPath ) ) {
45
+ const depFields = extractDepFields ( readJSON ( packageJsonPath , throwAtRead ) ) ;
46
+ depFieldCache . set ( packageJsonPath , depFields ) ;
47
+ }
48
+
49
+ return depFieldCache . get ( packageJsonPath ) ;
50
+ }
51
+
33
52
function getDependencies ( context , packageDir ) {
34
53
let paths = [ ] ;
35
54
try {
@@ -53,24 +72,21 @@ function getDependencies(context, packageDir) {
53
72
// use rule config to find package.json
54
73
paths . forEach ( dir => {
55
74
const packageJsonPath = path . join ( dir , 'package.json' ) ;
56
- if ( ! depFieldCache . has ( packageJsonPath ) ) {
57
- const depFields = extractDepFields (
58
- JSON . parse ( fs . readFileSync ( packageJsonPath , 'utf8' ) ) ,
59
- ) ;
60
- depFieldCache . set ( packageJsonPath , depFields ) ;
61
- }
62
- const _packageContent = depFieldCache . get ( packageJsonPath ) ;
75
+ const _packageContent = getPackageDepFields ( packageJsonPath , true ) ;
63
76
Object . keys ( packageContent ) . forEach ( depsKey =>
64
77
Object . assign ( packageContent [ depsKey ] , _packageContent [ depsKey ] ) ,
65
78
) ;
66
79
} ) ;
67
80
} else {
81
+ const packageJsonPath = pkgUp ( {
82
+ cwd : context . getPhysicalFilename ? context . getPhysicalFilename ( ) : context . getFilename ( ) ,
83
+ normalize : false ,
84
+ } ) ;
85
+
68
86
// use closest package.json
69
87
Object . assign (
70
88
packageContent ,
71
- extractDepFields (
72
- readPkgUp ( { cwd : context . getPhysicalFilename ? context . getPhysicalFilename ( ) : context . getFilename ( ) , normalize : false } ) . pkg ,
73
- ) ,
89
+ getPackageDepFields ( packageJsonPath , false ) ,
74
90
) ;
75
91
}
76
92
@@ -267,4 +283,8 @@ module.exports = {
267
283
reportIfMissing ( context , deps , depsOptions , node , source . value ) ;
268
284
} , { commonjs : true } ) ;
269
285
} ,
286
+
287
+ 'Program:exit' ( ) {
288
+ depFieldCache . clear ( ) ;
289
+ } ,
270
290
} ;
0 commit comments