/
lint.js
600 lines (501 loc) · 18.8 KB
/
lint.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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
#!/usr/bin/env node
/**
* @file Entry point of the linter-bundle.
*/
import { createRequire } from 'node:module';
import * as path from 'node:path';
import * as tty from 'node:tty';
import { fileURLToPath } from 'node:url';
import micromatch from 'micromatch';
import { getGitFiles } from './helper/get-git-files.js';
import { getOutdatedDependencies } from './helper/get-outdated-dependencies.js';
import { getOutdatedOverrides } from './helper/get-outdated-overrides.js';
import { getStylelintPath } from './helper/get-stylelint-path.js';
import { isNpmOrYarn } from './helper/is-npm-or-yarn.js';
import { linterBundleConfig } from './helper/linter-bundle-config.js';
import { runProcess } from './helper/run-process.js';
const require = createRequire(import.meta.url);
const dirname = path.dirname(fileURLToPath(import.meta.url));
/** @typedef {'files' | 'tsc' | 'ts' | 'sass' | 'md' | 'audit'} TaskNames */
/** @typedef {Partial<Record<string, (string | boolean)[]>>} TaskConfig */
/** @typedef {import('./helper/run-process.js').ProcessResult} ProcessResult */
/** @typedef {{ taskName: TaskNames; taskConfig: TaskConfig; }} TaskNameAndConfig */
/** @typedef {TaskNameAndConfig & { command: string; options?: import('child_process').ExecOptions; }} TaskSetup */
/** @typedef {{ jobTitle: string; taskSetup: TaskSetup; job: Promise<ProcessResult>; }} Job */
const isTerminal = tty.isatty(1);
const npmOrYarn = await isNpmOrYarn();
await (async () => {
if (!await validateEnvironment()) {
return;
}
/** @type {Job[]} */
const jobs = await Promise.all(getTasksToRun(process.argv.splice(2)).map(async ({ taskName, taskConfig }) => {
switch (taskName) {
case 'files':
return runFilesTask(taskName, taskConfig);
case 'tsc':
return runTypeScriptCompilerTask(taskName, taskConfig);
case 'ts':
return runESLintTask(taskName, taskConfig);
case 'sass':
return runStylelintTask(taskName, taskConfig);
case 'md':
return runMarkdownTask(taskName, taskConfig);
case 'audit':
return runAuditTask(taskName, taskConfig);
default:
}
throw new Error(`"${taskName}" is not a valid task.`);
}));
const totalStartTimestamp = performance.now();
let showTimingForAllJobs = true;
for (const { jobTitle, taskSetup, job } of jobs) {
process.stdout.write(jobTitle);
// eslint-disable-next-line no-await-in-loop -- Replace by `for await (const { ... } of jobs) {` as soon as Node.js supports it
const { code, stdout, stderr, runtime } = await job;
const trimmedError = stderr.trim();
if (code !== 0 || trimmedError !== '' || getConfigValue(taskSetup.taskName, taskSetup.taskConfig, 'verbose')?.[0]) {
process.stdout.write('\n');
if (stdout) {
process.stdout.write(`${stdout.trim()}\n`);
}
if (stderr) {
process.stderr.write(`${trimmedError}\n`);
}
}
if (code !== 0 && getConfigValue(taskSetup.taskName, taskSetup.taskConfig, 'verbose')?.[0]) {
if (isTerminal) {
process.stderr.write(`\n[lint ${taskSetup.taskName}] \u001B[31mProblems detected\u001B[39m\n`);
}
else {
process.stderr.write(`\n[lint ${taskSetup.taskName}] Problems detected\n`);
}
}
if (getConfigValue(taskSetup.taskName, taskSetup.taskConfig, 'timing')?.[0]) {
process.stdout.write(`\nJob finished after ${((runtime) / 1000).toFixed(1)}s\n`);
}
else {
showTimingForAllJobs = false;
}
if (process.exitCode === undefined || code > process.exitCode) {
process.exitCode = code;
}
}
if (showTimingForAllJobs) {
process.stdout.write(`\nTask finished after ${((performance.now() - totalStartTimestamp) / 1000).toFixed(1)}s\n`);
}
process.stdout.write('\n');
})();
/**
* Runs the `files` task.
*
* @param {TaskNameAndConfig['taskName']} taskName - Name of the task as used in the command line
* @param {TaskNameAndConfig['taskConfig']} taskConfig - Configuration of the task
* @returns {Promise<Job>} Shell job
*/
async function runFilesTask (taskName, taskConfig) {
const newTaskConfig = {
include: getConfigValue(taskName, taskConfig, 'include'),
git: getConfigValue(taskName, taskConfig, 'git')
};
const includes = await getIncludes(newTaskConfig);
if (!includes && taskConfig['git']?.[0]) {
return generateDummyJobOutput(taskName, newTaskConfig, {
stderr: 'No relevant files changed.'
});
}
return runTask({
taskName,
taskConfig: newTaskConfig,
command: `node "${path.resolve(dirname, './files/index.js')}" ${includes}`
});
}
/**
* Runs the `tsc` task.
*
* @param {TaskNames} taskName - Name of the task as used in the command line
* @param {TaskNameAndConfig['taskConfig']} taskConfig - Configuration of the task
* @returns {Promise<Job>} Shell job
*/
async function runTypeScriptCompilerTask (taskName, taskConfig) {
const newTaskConfig = {
tsconfig: getConfigValue(taskName, taskConfig, 'tsconfig')
};
return runTask({
taskName,
taskConfig: newTaskConfig,
command: [
'node',
`"${require.resolve('typescript/bin/tsc')}"`,
'--skipLibCheck',
'--noEmit',
(newTaskConfig.tsconfig?.[0] ? `--project ${newTaskConfig.tsconfig[0]}` : undefined)
].filter((argument) => Boolean(argument)).join(' ')
});
}
/**
* Runs the `ts` task.
*
* @param {TaskNameAndConfig['taskName']} taskName - Name of the task as used in the command line
* @param {TaskNameAndConfig['taskConfig']} taskConfig - Configuration of the task
* @returns {Promise<Job>} Shell job
*/
async function runESLintTask (taskName, taskConfig) {
const newTaskConfig = {
tsconfig: getConfigValue(taskName, taskConfig, 'tsconfig'),
include: getConfigValue(taskName, taskConfig, 'include'),
exclude: getConfigValue(taskName, taskConfig, 'exclude'),
git: getConfigValue(taskName, taskConfig, 'git')
};
const includes = await getIncludes(newTaskConfig, '**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx}');
if (!includes) {
return generateDummyJobOutput(taskName, newTaskConfig, {
stderr: 'No relevant files for ESLint changed.'
});
}
return runTask({
taskName,
command: [
'node',
`"${path.join(path.dirname(require.resolve('eslint')), '../bin/eslint.js')}"`,
includes,
newTaskConfig.exclude?.map((exclude) => `--ignore-pattern ${exclude}`).join(' '),
`--rulesdir "${path.resolve(dirname, './eslint/rules/')}"`,
'--format unix',
`--resolve-plugins-relative-to "${dirname}"`
].filter((argument) => Boolean(argument)).join(' '),
taskConfig: newTaskConfig,
options: {
env: {
TIMING: '10', // Show timing information about the 10 slowest rules
TSCONFIG: (typeof newTaskConfig.tsconfig?.[0] === 'string' ? newTaskConfig.tsconfig[0] : undefined)
}
}
});
}
/**
* Runs the `sass` task.
*
* @param {TaskNameAndConfig['taskName']} taskName - Name of the task as used in the command line
* @param {TaskNameAndConfig['taskConfig']} taskConfig - Configuration of the task
* @returns {Promise<Job>} Shell job
*/
async function runStylelintTask (taskName, taskConfig) {
const newTaskConfig = {
include: getConfigValue(taskName, taskConfig, 'include'),
git: getConfigValue(taskName, taskConfig, 'git'),
verbose: getConfigValue(taskName, taskConfig, 'verbose')
};
const includes = await getIncludes(newTaskConfig, 'src/**/*.scss');
if (!includes) {
return generateDummyJobOutput(taskName, newTaskConfig, {
stderr: 'No relevant files for Stylelint changed.'
});
}
const stylelintBinPath = await getStylelintPath();
if (stylelintBinPath === null) {
return generateDummyJobOutput(taskName, newTaskConfig, {
stderr: 'Stylelint CLI script not found.'
});
}
return runTask({
taskName,
taskConfig: newTaskConfig,
command: [
'node',
`"${stylelintBinPath}"`,
includes,
(newTaskConfig.verbose?.[0] ? '--verbose' : undefined),
'--formatter unix'
].filter((argument) => Boolean(argument)).join(' ')
});
}
/**
* Runs the `md` task.
*
* @param {TaskNameAndConfig['taskName']} taskName - Name of the task as used in the command line
* @param {TaskNameAndConfig['taskConfig']} taskConfig - Configuration of the task
* @returns {Promise<Job>} Shell job
*/
async function runMarkdownTask (taskName, taskConfig) {
const newTaskConfig = {
include: getConfigValue(taskName, taskConfig, 'include'),
git: getConfigValue(taskName, taskConfig, 'git')
};
const includes = await getIncludes(newTaskConfig, '**/*.md');
if (!includes) {
return generateDummyJobOutput(taskName, newTaskConfig, {
stderr: 'No relevant files for Markdownlint changed.'
});
}
return runTask({
taskName,
taskConfig: newTaskConfig,
command: [
'node',
`"${require.resolve('markdownlint-cli/markdownlint.js')}"`,
includes,
'--ignore node_modules'
].filter((argument) => Boolean(argument)).join(' ')
});
}
/**
* Runs the `audit` task.
*
* @param {TaskNameAndConfig['taskName']} taskName - Name of the task as used in the command line
* @param {TaskNameAndConfig['taskConfig']} taskConfig - Configuration of the task
* @returns {Promise<Job>} Shell job
*/
async function runAuditTask (taskName, taskConfig) {
const newTaskConfig = {
minSeverity: getConfigValue(taskName, taskConfig, 'minSeverity'),
exclude: getConfigValue(taskName, taskConfig, 'exclude')
};
switch (npmOrYarn) {
case 'npm':
return runTask({
taskName,
taskConfig: newTaskConfig,
command: [
'npx',
'--yes',
'--',
'better-npm-audit@3.7.3',
'audit',
`-l ${newTaskConfig.minSeverity?.[0] ?? 'moderate'}`,
'-p',
newTaskConfig.exclude?.map((exclude) => `-i ${exclude}`).join(' ')
].filter((argument) => Boolean(argument)).join(' ')
});
case 'yarn':
return runTask({
taskName,
taskConfig: newTaskConfig,
command: [
'npx',
'--yes',
'--',
'improved-yarn-audit@3.0.0',
`--min-severity ${newTaskConfig.minSeverity?.[0] ?? 'moderate'}`,
'--fail-on-missing-exclusions',
'--ignore-dev-deps',
newTaskConfig.exclude?.map((exclude) => `--exclude ${exclude}`).join(' ')
].filter((argument) => Boolean(argument)).join(' ')
});
case 'both':
return generateDummyJobOutput(taskName, newTaskConfig, {
code: 1,
stderr: 'A "package-lock.json" and "yarn.lock" have been found. Use only one package manager within the project to avoid potential conflicts.'
});
default:
return generateDummyJobOutput(taskName, newTaskConfig, {
code: 1,
stderr: 'Neither a "package-lock.json" nor a "yarn.lock" have been found.'
});
}
}
/**
* Ensures that the environment in which the linter is running has the correct versions of the required dependencies.
*
* @returns {Promise<boolean>} Returns `true` if the environment is valid, otherwise `false` is returned
*/
async function validateEnvironment () {
const outdatedOverrides = await getOutdatedOverrides();
if (outdatedOverrides.overrides.length > 0 || outdatedOverrides.resolutions.length > 0) {
if (outdatedOverrides.overrides.length > 0) {
process.stderr.write(`Outdated "overrides" in package.json detected:\n- ${outdatedOverrides.overrides.map((dependency) => `${dependency.name}: ${dependency.configuredVersion} is configured, but ${dependency.expectedVersion} is expected`).join('\n- ')}\n\n`);
}
if (outdatedOverrides.resolutions.length > 0) {
process.stderr.write(`Outdated "resolutions" in package.json detected:\n- ${outdatedOverrides.resolutions.map((dependency) => `${dependency.name}: ${dependency.configuredVersion} is configured, but ${dependency.expectedVersion} is expected`).join('\n- ')}\n\n`);
}
process.exitCode = 1;
return false;
}
const outdatedDependencies = await getOutdatedDependencies();
const missingOverrides = outdatedDependencies.filter(({ name }) => !(npmOrYarn === 'npm' && outdatedOverrides.overrides.some((override) => name === override.name)) && !(npmOrYarn === 'yarn' && outdatedOverrides.resolutions.some((override) => name === override.name)));
if (missingOverrides.length > 0) {
let installCommand;
let propertyName;
if (npmOrYarn === 'yarn') {
installCommand = 'yarn install';
propertyName = 'resolutions';
}
else {
installCommand = 'npm install --no-package-lock';
propertyName = 'overrides';
}
process.stderr.write(`The installed version of ${missingOverrides.length === 1 ? 'one dependency' : `${missingOverrides.length} dependencies`} does not match to the version required by the linter-bundle:\n`);
process.stderr.write(`- ${missingOverrides.map((dependency) => `${dependency.name}: ${dependency.configuredVersion} is installed, but ${dependency.expectedVersion} is expected`).join('\n- ')}\n\n`);
process.stderr.write(`This could be caused by forgetting to execute \`${installCommand}\` after changing a version number in the package.json, or by some other package shipping outdated versions of the ${missingOverrides.length === 1 ? 'dependency' : 'dependencies'}.\n`);
process.stderr.write('If another package is causing this problem, you can fix it by adding the following entry to your package.json:\n');
process.stderr.write(`{\n "${propertyName}": {\n ${missingOverrides.map((dependency) => `"${dependency.name}": "${dependency.expectedVersion}"`).join(',\n ')}\n }\n}\n\n`);
process.exitCode = 1;
return false;
}
return true;
}
/**
* Extracts the tasks which should be run from the command-line arguments passed in.
*
* @param {string[]} argv - Command-line arguments (usual `process.argv.splice(2)`)
* @returns {TaskNameAndConfig[]} The task execution setup
* @throws {Error} If no task has be specified in the arguments
*/
function getTasksToRun (argv) {
const TASKS = new Set(['tsc', 'ts', 'sass', 'md', 'audit', 'files']);
const ARG_REGEXP = /^--([^=]+)(?:=(.+))?$/u;
/** @type {TaskNameAndConfig | null} */
let currentTask = null;
/** @type {TaskNameAndConfig[]} */
const tasksToRun = [];
/** @type {Record<string, (string | boolean)[]>} */
const generalConfig = {};
for (const argument of argv) {
if (TASKS.has(argument)) {
currentTask = {
taskName: /** @type {TaskNames} */(argument),
taskConfig: { ...generalConfig }
};
tasksToRun.push(currentTask);
continue;
}
const [, name, value = true] = /** @type {[string | undefined, string | undefined, string | true | undefined]} */(/** @type {any} */(ARG_REGEXP.exec(argument)) ?? []);
if (name === undefined) {
throw new Error(`Unknown argument "${argument}"`);
}
// Converts e.g. "MIN-SEVERITY" into "minSeverity"
const normalizedName = name.toLowerCase().replace(/-./gu, (match) => match[1].toUpperCase());
if (currentTask === null) {
if (!(normalizedName in generalConfig)) {
generalConfig[normalizedName] = [];
}
generalConfig[normalizedName].push(value);
}
else {
if (!(normalizedName in currentTask.taskConfig)) {
currentTask.taskConfig[normalizedName] = [];
}
/** @type {(string | boolean)[]} */(currentTask.taskConfig[normalizedName]).push(value);
}
}
return tasksToRun;
}
/**
* Returns a list of changed files, based on the Git-diff result and the glob pattern to be used in the command-line.
*
* @param {TaskConfig} taskConfig - Linter configuration
* @param {string | undefined} [pattern] - Glob pattern
* @returns {Promise<string>} Space-separated file names in double-quotes to be used in the command-line, or an empty string if no file matches
*/
async function getIncludes (taskConfig, pattern) {
const include = taskConfig['include'];
let includedFiles = (Array.isArray(include) && include.length > 0 ? /** @type {string[]} */(include.filter((item) => typeof item === 'string')) : undefined);
if (taskConfig['git']?.[0]) {
const gitFiles = await getGitFiles();
if (includedFiles) {
includedFiles = micromatch(gitFiles, includedFiles);
}
else if (pattern) {
includedFiles = micromatch(gitFiles, [pattern]);
}
else {
includedFiles = gitFiles;
}
if (includedFiles.length === 0) {
return '';
}
}
if (!includedFiles) {
return (pattern ? `"${pattern}"` : '');
}
return `"${includedFiles.join('" "')}"`;
}
/**
* Executes a task asynchronously.
*
* @param {TaskSetup} setup - The task execution setup
* @returns {Job} Shell job
*/
function runTask (setup) {
return {
jobTitle: getJobTitle(setup),
taskSetup: setup,
job: runProcess(setup.command, setup.options)
};
}
/**
* Returns a job configuration which does not run any task, but just returns the given `output`.
*
* @param {TaskNames} taskName - Name of the task as used in the command line
* @param {TaskConfig} taskConfig - The configuration of the task
* @param {{ code?: number; stdout?: string; stderr?: string; }} output - The output which should be returned as result of the job
* @returns {Job} Shell job
*/
function generateDummyJobOutput (taskName, taskConfig, output) {
return {
jobTitle: getJobTitle({
taskName,
taskConfig,
command: ''
}),
taskSetup: {
taskName,
taskConfig,
command: ''
},
job: Promise.resolve({
code: 0,
stdout: '',
stderr: '',
runtime: 0,
...output
})
};
}
/**
* Returns the title (command line string) of a specific job.
*
* @param {TaskSetup} setup - The task execution setup
* @returns {string} The title of the job with a leading line-break and two trailing line-breaks
*/
function getJobTitle (setup) {
/** @type {string} */
const additionalArgumentString = Object.entries(setup.taskConfig).filter(([, values]) => values !== undefined).map(([name, values]) => (Array.isArray(values) ? values.map((value) => (value === true ? `--${name}` : `--${name}="${value}"`)).join(' ') : '')).join(' ');
return `\n[lint ${setup.taskName}${(additionalArgumentString.length > 0 ? ` ${additionalArgumentString}` : '')}] ${setup.command}\n`;
}
/**
* Returns a configuration option value based on the command line arguments and the `.linter-bundle.js` configuration.
*
* @param {TaskNames} taskName - Name of the task as used in the command line
* @param {TaskConfig} taskConfig - Configuration of a task
* @param {string} optionName - Configuration option name
* @returns {(string | boolean)[] | undefined} Configuration option value
*/
function getConfigValue (taskName, taskConfig, optionName) {
if (optionName in taskConfig) {
return taskConfig[optionName];
}
if (taskName in linterBundleConfig) {
const specificConfig = linterBundleConfig[/** @type {keyof typeof linterBundleConfig} */(taskName)];
if (typeof specificConfig === 'object' && optionName in specificConfig) {
// eslint-disable-next-line jsdoc/no-undefined-types -- False positive "The type 'specificConfig' is undefined."
const configValue = specificConfig[/** @type {keyof typeof specificConfig} */(optionName)];
if (Array.isArray(configValue)) {
return configValue;
}
else if (typeof configValue === 'boolean' || typeof configValue === 'string') {
return [configValue];
}
}
}
if (optionName in linterBundleConfig) {
const configValue = linterBundleConfig[/** @type {keyof typeof linterBundleConfig} */(optionName)];
if (Array.isArray(configValue)) {
return configValue;
}
else if (typeof configValue === 'boolean' || typeof configValue === 'string') {
return [configValue];
}
}
return;
}