-
-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathlinter.js
More file actions
320 lines (273 loc) · 8.51 KB
/
Copy pathlinter.js
File metadata and controls
320 lines (273 loc) · 8.51 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
const { dirname, isAbsolute, join } = require("node:path");
const ESLintError = require("./ESLintError");
const applySuppressions = require("./applySuppressions");
const { getESLint } = require("./getESLint");
const { arrify } = require("./utils");
/** @typedef {import("eslint").ESLint} ESLint */
/** @typedef {import("eslint").ESLint.Formatter} Formatter */
/** @typedef {import("eslint").ESLint.LintResult} LintResult */
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").Compilation} Compilation */
/** @typedef {import("./options").Options} Options */
/** @typedef {import("./options").FormatterFunction} FormatterFunction */
/** @typedef {(compilation: Compilation) => Promise<void>} GenerateReport */
/** @typedef {{ errors?: ESLintError, warnings?: ESLintError, generateReportAsset?: GenerateReport }} Report */
/** @typedef {() => Promise<Report>} Reporter */
/** @typedef {(files: string | string[]) => void} Linter */
/** @typedef {{ [files: string]: LintResult }} LintResultMap */
/** @type {WeakMap<Compiler, LintResultMap>} */
const resultStorage = new WeakMap();
/**
* @param {Compilation} compilation compilation
* @returns {LintResultMap} lint result map
*/
function getResultStorage({ compiler }) {
let storage = resultStorage.get(compiler);
if (!storage) {
resultStorage.set(compiler, (storage = {}));
}
return storage;
}
/**
* @param {Promise<LintResult[]>[]} results results
* @returns {Promise<LintResult[]>} flatted results
*/
async function flatten(results) {
/**
* @param {LintResult[]} acc acc
* @param {LintResult[]} list list
* @returns {LintResult[]} result
*/
const flat = (acc, list) => [...acc, ...list];
return (await Promise.all(results)).reduce(flat, []);
}
/**
* @param {ESLint} eslint eslint
* @param {LintResult[]} results results
* @returns {Promise<LintResult[]>} result without warnings
*/
async function removeIgnoredWarnings(eslint, results) {
const filterPromises = results.map(async (result) => {
// Short circuit the call to isPathIgnored.
// fatal is false for ignored file warnings.
// ruleId is unset for internal ESLint errors.
// line is unset for warnings not involving file contents.
const { messages, warningCount, errorCount, filePath } = result;
const [firstMessage] = messages;
const hasWarning = warningCount === 1 && errorCount === 0;
const ignored =
messages.length === 0 ||
(hasWarning &&
!firstMessage.fatal &&
!firstMessage.ruleId &&
!firstMessage.line &&
(await eslint.isPathIgnored(filePath)));
return ignored ? false : result;
});
return (await Promise.all(filterPromises)).filter(
(result) => result !== false,
);
}
/**
* @param {ESLint} eslint eslint
* @param {string | FormatterFunction=} formatter formatter
* @returns {Promise<Formatter>} loaded formatter
*/
async function loadFormatter(eslint, formatter) {
if (typeof formatter === "function") {
return { format: formatter };
}
if (typeof formatter === "string") {
try {
return eslint.loadFormatter(formatter);
} catch {
// Load the default formatter.
}
}
return eslint.loadFormatter();
}
/**
* @param {Formatter} formatter formatter
* @param {{ errors: LintResult[], warnings: LintResult[] }} results results
* @returns {Promise<{ errors?: ESLintError, warnings?: ESLintError }>} errors and warnings
*/
async function formatResults(formatter, results) {
let errors;
let warnings;
if (results.warnings.length > 0) {
warnings = new ESLintError(await formatter.format(results.warnings));
}
if (results.errors.length > 0) {
errors = new ESLintError(await formatter.format(results.errors));
}
return {
errors,
warnings,
};
}
/**
* @param {LintResult} file file
* @returns {boolean} true when has errors, otherwise false
*/
function fileHasErrors(file) {
return file.errorCount > 0;
}
/**
* @param {LintResult} file file
* @returns {boolean} true when has warnings, otherwise false
*/
function fileHasWarnings(file) {
return file.warningCount > 0;
}
/**
* @param {Options} options options results
* @param {LintResult[]} results results
* @returns {{ errors: LintResult[], warnings: LintResult[] }} parsed errors and warnings
*/
function parseResults(options, results) {
/** @type {LintResult[]} */
const errors = [];
/** @type {LintResult[]} */
const warnings = [];
for (const file of results) {
if (fileHasErrors(file)) {
const messages = file.messages.filter(
(message) => options.emitError && message.severity === 2,
);
if (messages.length > 0) {
errors.push({ ...file, messages });
}
}
if (fileHasWarnings(file)) {
const messages = file.messages.filter(
(message) => options.emitWarning && message.severity === 1,
);
if (messages.length > 0) {
warnings.push({ ...file, messages });
}
}
}
return {
errors,
warnings,
};
}
/**
* @param {string | undefined} key a cache key
* @param {Options} options options
* @param {Compilation} compilation compilation
* @returns {Promise<{ lint: Linter, report: Reporter, threads: number }>} linter with additional functions
*/
async function linter(key, options, compilation) {
/** @type {ESLint} */
let eslint;
/** @type {(files: string | string[]) => Promise<LintResult[]>} */
let lintFiles;
/** @type {() => Promise<void>} */
let cleanup;
/** @type number */
let threads;
/** @type {Promise<LintResult[]>[]} */
const rawResults = [];
const crossRunResultStorage = getResultStorage(compilation);
try {
({ eslint, lintFiles, cleanup, threads } = await getESLint(key, options));
} catch (err) {
throw new ESLintError(err.message);
}
/**
* @param {string | string[]} files files
*/
function lint(files) {
for (const file of arrify(files)) {
delete crossRunResultStorage[file];
}
rawResults.push(
lintFiles(files).catch((err) => {
compilation.errors.push(new ESLintError(err.message));
return [];
}),
);
}
/**
* @returns {Promise<Report>} report
*/
async function report() {
// Filter out ignored files.
let results = await removeIgnoredWarnings(
eslint,
// Get the current results, resetting the rawResults to empty
await flatten(rawResults.splice(0)),
);
await cleanup();
// Apply suppressions from eslint-suppressions.json if available
results = await applySuppressions(results, options);
for (const result of results) {
crossRunResultStorage[result.filePath] = result;
}
results = Object.values(crossRunResultStorage);
// do not analyze if there are no results or eslint config
if (!results || results.length < 1) {
return {};
}
const formatter = await loadFormatter(eslint, options.formatter);
const { errors, warnings } = await formatResults(
formatter,
parseResults(options, results),
);
/**
* @param {Compilation} compilation compilation
* @returns {Promise<void>}
*/
async function generateReportAsset({ compiler }) {
const { outputReport } = options;
/**
* @param {string} name name
* @param {string | Buffer} content content
* @returns {Promise<void>}
*/
const save = (name, content) =>
/** @type {Promise<void>} */
(
new Promise((finish, bail) => {
if (!compiler.outputFileSystem) return;
const { mkdir, writeFile } = compiler.outputFileSystem;
mkdir(dirname(name), { recursive: true }, (err) => {
/* istanbul ignore if */
if (err) {
bail(err);
} else {
writeFile(name, content, (/** @type {unknown} */ err2) => {
/* istanbul ignore if */
if (err2) bail(err2);
else finish();
});
}
});
})
);
if (!outputReport || !outputReport.filePath) {
return;
}
const content = await (outputReport.formatter
? (await loadFormatter(eslint, outputReport.formatter)).format(results)
: formatter.format(results));
let { filePath } = outputReport;
if (!isAbsolute(filePath)) {
filePath = join(compiler.outputPath, filePath);
}
await save(filePath, content);
}
return {
errors,
warnings,
generateReportAsset,
};
}
return {
lint,
report,
threads,
};
}
module.exports = linter;