-
Notifications
You must be signed in to change notification settings - Fork 727
/
Copy pathlint-dependencies.js
279 lines (231 loc) · 7.93 KB
/
lint-dependencies.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/**
* This script finds all the `import` and `require` of a packages
* and checks that there's a dependency for each one of them in
* the `package.json`.
*/
const fs = require('fs-extra');
const path = require('path');
const globby = require('globby');
const builtIn = require('builtin-modules');
const typeDependencies = new Set([
'har-format',
'estree-jsx',
'request',
'vscode'
]);
const ignoredDependencies = new Set([
'@hint/configuration-development',
'@hint/configuration-web-recommended',
'@hint/connector-jsdom',
'@hint/connector-local',
'@hint/connector-puppeteer',
'@hint/utils-create-server',
'@hint/utils-tests-helpers',
'@types/chrome',
'@types/node',
'@typescript-eslint/eslint-plugin',
'@typescript-eslint/parser',
'ava',
'canvas',
'copyfiles',
'crypto-browserify',
'eslint',
'eslint-plugin-import',
'eslint-plugin-markdown',
'eslint-plugin-react-hooks',
'hint',
'npm-run-all',
'nyc',
'os-browserify',
'path-browserify',
'rimraf',
'setimmediate',
'stream-browserify',
'style-loader',
'typescript',
'typed-css-modules',
'vm-browserify',
'vsce',
'vscode-languageclient',
'web-ext',
'webpack',
'webpack-cli',
...builtIn
]);
const regexps = [
/import[\s\w\d{},*]*?'([a-z0-9_\-@/.]+)';/gi, // `import * as something from 'something';`
/import\('([a-z0-9_\-@/.]+)'\)/gi, // `import('something');`
/require(?:\.resolve)?\('([a-z0-9_\-@/.]+)'\)/gi, // `const something = require('something');` || `const something = require.resolve('something');`
/(?:loader|use):\s+'([a-z0-9_\-@/.]+)'/gi, // webpack config: `loader: 'ts-loader'` `use: 'raw-loader'`
/use:\s+\[?\s*'([a-z0-9_\-@/.]+)'/gmi // webpack config, `use` can accept an array
];
const getPackages = async () => {
const pkgs = await globby(['packages/*'], {
absolute: true,
onlyFiles: false
});
console.log(`Packages found: ${pkgs.length}`);
return pkgs;
};
const getDependencies = (pkg) => {
const depArray = [
...builtIn,
...Object.keys(pkg.dependencies || []),
...Object.keys(pkg.devDependencies || []),
...Object.keys(pkg.peerDependencies || []),
...Object.keys(pkg.optionalDependencies || [])
];
const dependencies = new Set(depArray);
return dependencies;
};
const getCodeContent = async (rawPkgPath) => {
const pkgPath = rawPkgPath.replace(/\\/g, '/');
const files = await globby([
`${pkgPath}/**/*.ts`,
`${pkgPath}/**/*.tsx`,
`${pkgPath}/**/*.js`,
`${pkgPath}/**/*.jsx`,
`!${pkgPath}/webhint.js`,
`!${pkgPath}/dist/**/*`,
`!${pkgPath}/node_modules/**/*` // needed when we are inside a package like extension-vscode
], { gitignore: false });
const contents = new Map();
const readPromises = files.map((file) => {
return fs.readFile(file, 'utf-8')
.then((content) => {
contents.set(file, content);
});
});
await Promise.all(readPromises);
return contents;
};
const processFile = (content, dependencies) => {
const missingDependencies = new Set();
regexps.forEach((regex) => {
let match;
while ((match = regex.exec(content)) !== null) {
const [, dependency] = match;
if (dependency.startsWith('.')) {
continue;
}
/**
* Only the first part of the dependecy is needed:
* E.g.: `import * from 'hint/dist/src/types'`
* `hint`
*
* The exception are the scoped packages:
* E.g.: `import * from '@hint/utils'`
* `@hint/utils`
*/
const parts = dependency.split('/');
const root = dependency.startsWith('@') ?
`${parts[0]}/${parts[1]}` :
parts[0];
if (!dependencies.has(root) &&
!(typeDependencies.has(root) && dependencies.has(`@types/${root}`)) &&
!ignoredDependencies.has(root)
) {
missingDependencies.add(root);
}
}
});
return missingDependencies;
};
/**
*
* @param {Map<string,string>} files
*/
const getPackageDependencies = (files) => {
const usedDependencies = new Set();
/**
* special case for webhint configurations in tests:
* `parsers: ['manifest', 'css', 'sass']`
*
* The RegExp will match all the content inside `[]`
* so we will have to get the different parts later
* and add them individually.
*/
const parserRegex = /(parsers): \[([',\sa-z0-9]+)\]/gi;
[...regexps, parserRegex].forEach((regex) => {
let match;
for (const [, content] of files) {
while ((match = regex.exec(content)) !== null) {
let [, dependency, extra] = match;
// Especial handling of `parsers: ['manifest', 'css', 'sass']`
if (dependency === 'parsers') {
extra = extra.replace(/'/g, '');
const extras = extra.split(',');
extras.forEach((dep) => {
dependency = `@hint/parser-${dep.trim()}`;
usedDependencies.add(dependency);
});
} else {
const parts = dependency.split('/');
// E.g.: `@hint/utils/dist/src` --> `@hint/utils`
if (dependency.startsWith('@')) {
usedDependencies.add(`${parts[0]}/${parts[1]}`);
} else {
// E.g.: `hint/dist/src` --> `hint`
usedDependencies.add(parts[0]);
}
}
}
}
});
return usedDependencies;
};
const processPackage = async (pkgPath) => {
/**
* 1. Load package.json and get the dependencies, devDependencies and peerDependencies
* 2. Find all *.ts and *.js files ignoring node_modules
* 3. For each file search all imports and requires
* 4. Match content against dependencies
*/
const pkgJsonPath = path.join(pkgPath, 'package.json');
const pkg = require(pkgJsonPath);
const dependencies = getDependencies(pkg);
const files = await getCodeContent(pkgPath);
if (files.size === 0) {
console.log(`No files to process for "${pkgPath}"`);
return;
}
console.log(`Processing "${pkgPath}"`);
// Verify all require, import, etc. have a matching dependency
for (const [filePath, content] of files) {
const missingDependencies = processFile(content, dependencies);
if (missingDependencies.size > 0) {
missingDependencies.forEach((dependency) => {
console.error(`\t${dependency} missing in ${filePath}`);
});
process.exitCode = 1;
}
}
// Verify that all dependencies in `package.json` have a require, import, etc.
const usedDependencies = getPackageDependencies(files);
for (const dependency of dependencies) {
const used = usedDependencies.has(dependency.replace('@types/', '')) || // required to find unnecessary types
ignoredDependencies.has(dependency);
if (!used) {
console.error(`\t"${dependency}" is not necessary in ${pkgPath}/package.json`);
process.exitCode = 1;
}
}
};
const init = async () => {
/**
* If running from the root need to lint all packages,
* otherwise just the current package
*/
const pkgs = process.cwd() === path.join(__dirname, '..') ?
await getPackages() :
[process.cwd()];
for (const pkg of pkgs) {
await processPackage(pkg);
}
if (process.exitCode) {
console.error('Issues with depedendencies found. Please check output above.');
} else {
console.log('No dependency issues found.');
}
};
init();