๐Ÿ“ฆ microsoft / vscode

๐Ÿ“„ gulp-eslint.ts ยท 81 lines
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/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { ESLint } from 'eslint';
import fancyLog from 'fancy-log';
import { relative } from 'path';
import { Transform, type TransformOptions } from 'stream';

interface ESLintResults extends Array<ESLint.LintResult> {
	errorCount: number;
	warningCount: number;
}

interface EslintAction {
	(results: ESLintResults): void;
}

export default function eslint(action: EslintAction) {
	const linter = new ESLint({});
	const formatter = linter.loadFormatter('compact');

	const results: ESLintResults = Object.assign([], { errorCount: 0, warningCount: 0 });

	return createTransform(
		async (file, _enc, cb) => {
			const filePath = relative(process.cwd(), file.path);

			if (file.isNull()) {
				cb(null, file);
				return;
			}

			if (file.isStream()) {
				cb(new Error('vinyl files with Stream contents are not supported'));
				return;
			}

			try {
				// TODO: Should this be checked?
				if (await linter.isPathIgnored(filePath)) {
					cb(null, file);
					return;
				}

				const result = (await linter.lintText(file.contents.toString(), { filePath }))[0];
				results.push(result);
				results.errorCount += result.errorCount;
				results.warningCount += result.warningCount;

				const message = (await formatter).format([result]);
				if (message) {
					fancyLog(message);
				}
				cb(null, file);
			} catch (error) {
				cb(error);
			}
		},
		(done) => {
			try {
				action(results);
				done();
			} catch (error) {
				done(error);
			}
		});
}

function createTransform(
	transform: TransformOptions['transform'],
	flush: TransformOptions['flush']
): Transform {
	return new Transform({
		objectMode: true,
		transform,
		flush
	});
}