forked from palantir/tslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.ts
341 lines (296 loc) · 11.4 KB
/
runner.ts
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
/**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// tslint:disable strict-boolean-expressions (TODO: Fix up options)
import * as fs from "fs";
import * as glob from "glob";
import { filter as createMinimatchFilter, Minimatch } from "minimatch";
import * as path from "path";
import * as ts from "typescript";
import {
DEFAULT_CONFIG,
findConfiguration,
JSON_CONFIG_FILENAME,
} from "./configuration";
import { FatalError } from "./error";
import { LintResult } from "./index";
import { Linter } from "./linter";
import { flatMap } from "./utils";
export interface Options {
/**
* Path to a configuration file.
*/
config?: string;
/**
* Exclude globs from path expansion.
*/
exclude: string[];
/**
* File paths to lint.
*/
files: string[];
/**
* Whether to return status code 0 even if there are lint errors.
*/
force?: boolean;
/**
* Whether to fixes linting errors for select rules. This may overwrite linted files.
*/
fix?: boolean;
/**
* Output format.
*/
format?: string;
/**
* Formatters directory path.
*/
formattersDirectory?: string;
/**
* Whether to generate a tslint.json config file in the current working directory.
*/
init?: boolean;
/**
* Output file path.
*/
out?: string;
/**
* Whether to output absolute paths
*/
outputAbsolutePaths?: boolean;
/**
* tsconfig.json file.
*/
project?: string;
/**
* Rules directory paths.
*/
rulesDirectory?: string | string[];
/**
* Run the tests in the given directories to ensure a (custom) TSLint rule's output matches the expected output.
* When this property is `true` the `files` property is used to specify the directories from which the tests should be executed.
*/
test?: boolean;
/**
* Whether to enable type checking when linting a project.
*/
typeCheck?: boolean;
}
export const enum Status {
Ok = 0,
FatalError = 1,
LintError = 2,
}
export interface Logger {
log(message: string): void;
error(message: string): void;
}
export async function run(options: Options, logger: Logger): Promise<Status> {
try {
return await runWorker(options, logger);
} catch (error) {
if (error instanceof FatalError) {
logger.error(`${error.message}\n`);
return Status.FatalError;
}
throw error;
}
}
async function runWorker(options: Options, logger: Logger): Promise<Status> {
if (options.init) {
if (fs.existsSync(JSON_CONFIG_FILENAME)) {
throw new FatalError(`Cannot generate ${JSON_CONFIG_FILENAME}: file already exists`);
}
fs.writeFileSync(JSON_CONFIG_FILENAME, JSON.stringify(DEFAULT_CONFIG, undefined, " "));
return Status.Ok;
}
if (options.test) {
const test = await import("./test");
const results = test.runTests((options.files || []).map(trimSingleQuotes), options.rulesDirectory);
return test.consoleTestResultsHandler(results, logger) ? Status.Ok : Status.FatalError;
}
if (options.config && !fs.existsSync(options.config)) {
throw new FatalError(`Invalid option for configuration: ${options.config}`);
}
const { output, errorCount } = await runLinter(options, logger);
if (output && output.trim()) {
logger.log(`${output}\n`);
}
return options.force || errorCount === 0 ? Status.Ok : Status.LintError;
}
async function runLinter(options: Options, logger: Logger): Promise<LintResult> {
const { files, program } = resolveFilesAndProgram(options, logger);
// if type checking, run the type checker
if (program && options.typeCheck) {
const diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length !== 0) {
const message = diagnostics.map((d) => showDiagnostic(d, program, options.outputAbsolutePaths)).join("\n");
if (options.force) {
logger.error(`${message}\n`);
} else {
throw new FatalError(message);
}
}
}
return doLinting(options, files, program, logger);
}
function resolveFilesAndProgram(
{ files, project, exclude, outputAbsolutePaths }: Options,
logger: Logger,
): { files: string[]; program?: ts.Program } {
// remove single quotes which break matching on Windows when glob is passed in single quotes
exclude = exclude.map(trimSingleQuotes);
if (project === undefined) {
return { files: resolveGlobs(files, exclude, outputAbsolutePaths, logger) };
}
const projectPath = findTsconfig(project);
if (projectPath === undefined) {
throw new FatalError(`Invalid option for project: ${project}`);
}
exclude = exclude.map((pattern) => path.resolve(pattern));
const program = Linter.createProgram(projectPath);
let filesFound: string[];
if (files.length === 0) {
filesFound = filterFiles(Linter.getFileNames(program), exclude, false);
} else {
files = files.map((f) => path.resolve(f));
filesFound = filterFiles(program.getSourceFiles().map((f) => f.fileName), files, true);
filesFound = filterFiles(filesFound, exclude, false);
// find non-glob files that have no matching file in the project and are not excluded by any exclude pattern
for (const file of filterFiles(files, exclude, false)) {
if (!glob.hasMagic(file) && !filesFound.some(createMinimatchFilter(file))) {
if (fs.existsSync(file)) {
throw new FatalError(`'${file}' is not included in project.`);
}
logger.error(`'${file}' does not exist. This will be an error in TSLint 6.\n`); // TODO make this an error in v6.0.0
}
}
}
return { files: filesFound, program };
}
function filterFiles(files: string[], patterns: string[], include: boolean): string[] {
if (patterns.length === 0) {
return include ? [] : files;
}
const matcher = patterns.map((pattern) => new Minimatch(pattern, {dot: !include})); // `glob` always enables `dot` for ignore patterns
return files.filter((file) => include === matcher.some((pattern) => pattern.match(file)));
}
function resolveGlobs(files: string[], ignore: string[], outputAbsolutePaths: boolean | undefined, logger: Logger): string[] {
const results = flatMap(
files,
(file) => glob.sync(trimSingleQuotes(file), { ignore, nodir: true }),
);
// warn if `files` contains non-existent files, that are not patters and not excluded by any of the exclude patterns
for (const file of filterFiles(files, ignore, false)) {
if (!glob.hasMagic(file) && !results.some(createMinimatchFilter(file))) {
logger.error(`'${file}' does not exist. This will be an error in TSLint 6.\n`); // TODO make this an error in v6.0.0
}
}
const cwd = process.cwd();
return results.map((file) => outputAbsolutePaths ? path.resolve(cwd, file) : path.relative(cwd, file));
}
async function doLinting(options: Options, files: string[], program: ts.Program | undefined, logger: Logger): Promise<LintResult> {
const linter = new Linter(
{
fix: !!options.fix,
formatter: options.format,
formattersDirectory: options.formattersDirectory,
rulesDirectory: options.rulesDirectory,
},
program);
let lastFolder: string | undefined;
let configFile = options.config !== undefined ? findConfiguration(options.config).results : undefined;
for (const file of files) {
if (options.config === undefined) {
const folder = path.dirname(file);
if (lastFolder !== folder) {
configFile = findConfiguration(null, folder).results;
lastFolder = folder;
}
}
if (isFileExcluded(file)) {
continue;
}
let contents: string | undefined;
if (program !== undefined) {
const sourceFile = program.getSourceFile(file);
if (sourceFile !== undefined) {
contents = sourceFile.text;
}
} else {
contents = await tryReadFile(file, logger);
}
if (contents !== undefined) {
linter.lint(file, contents, configFile);
}
}
return linter.getResult();
function isFileExcluded(filepath: string) {
if (configFile === undefined || configFile.linterOptions == undefined || configFile.linterOptions.exclude == undefined) {
return false;
}
const fullPath = path.resolve(filepath);
return configFile.linterOptions.exclude.some((pattern) => new Minimatch(pattern).match(fullPath));
}
}
/** Read a file, but return undefined if it is an MPEG '.ts' file. */
async function tryReadFile(filename: string, logger: Logger): Promise<string | undefined> {
if (!fs.existsSync(filename)) {
throw new FatalError(`Unable to open file: ${filename}`);
}
const buffer = Buffer.allocUnsafe(256);
const fd = fs.openSync(filename, "r");
try {
fs.readSync(fd, buffer, 0, 256, 0);
if (buffer.readInt8(0) === 0x47 && buffer.readInt8(188) === 0x47) {
// MPEG transport streams use the '.ts' file extension. They use 0x47 as the frame
// separator, repeating every 188 bytes. It is unlikely to find that pattern in
// TypeScript source, so tslint ignores files with the specific pattern.
logger.error(`${filename}: ignoring MPEG transport stream\n`);
return undefined;
}
} finally {
fs.closeSync(fd);
}
return fs.readFileSync(filename, "utf8");
}
function showDiagnostic({ file, start, category, messageText }: ts.Diagnostic, program: ts.Program, outputAbsolutePaths?: boolean): string {
let message = ts.DiagnosticCategory[category];
if (file !== undefined && start !== undefined) {
const {line, character} = file.getLineAndCharacterOfPosition(start);
const currentDirectory = program.getCurrentDirectory();
const filePath = outputAbsolutePaths
? path.resolve(currentDirectory, file.fileName)
: path.relative(currentDirectory, file.fileName);
message += ` at ${filePath}:${line + 1}:${character + 1}:`;
}
return `${message} ${ts.flattenDiagnosticMessageText(messageText, "\n")}`;
}
function trimSingleQuotes(str: string): string {
return str.replace(/^'|'$/g, "");
}
function findTsconfig(project: string): string | undefined {
try {
const stats = fs.statSync(project); // throws if file does not exist
if (!stats.isDirectory()) {
return project;
}
const projectFile = path.join(project, "tsconfig.json");
fs.accessSync(projectFile); // throws if file does not exist
return projectFile;
} catch (e) {
return undefined;
}
}