forked from palantir/tslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.ts
296 lines (254 loc) · 8.33 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
/**
* @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 path from "path";
import * as ts from "typescript";
import {
DEFAULT_CONFIG,
findConfiguration,
findConfigurationPath,
isFileExcluded,
JSON_CONFIG_FILENAME,
stringifyConfiguration,
} from "./configuration";
import { FatalError } from "./error";
import { tryReadFile } from "./files/reading";
import { resolveFilesAndProgram } from "./files/resolution";
import { LintResult } from "./index";
import { Linter } from "./linter";
import { trimSingleQuotes } 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;
/**
* Outputs the configuration to be used instead of linting.
*/
printConfig?: boolean;
/**
* tsconfig.json file.
*/
project?: string;
/**
* Whether to hide warnings
*/
quiet?: boolean;
/**
* 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.printConfig) {
return printConfiguration(options, logger);
}
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 printConfiguration(options: Options, logger: Logger): Promise<Status> {
const { files } = options;
if (files.length !== 1) {
throw new FatalError(`--print-config must be run with exactly one file`);
}
const configurationPath =
options.config === undefined ? findConfigurationPath(null, files[0]) : options.config;
if (configurationPath === undefined) {
throw new FatalError(
`Could not find configuration path. Try passing a --config to your tslint.json.`,
);
}
const configuration = findConfiguration(configurationPath, files[0]).results;
if (configuration === undefined) {
throw new FatalError(`Could not find configuration for '${files[1]}`);
}
logger.log(`${stringifyConfiguration(configuration)}\n`);
return Status.Ok;
}
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);
}
async function doLinting(
options: Options,
files: string[],
program: ts.Program | undefined,
logger: Logger,
): Promise<LintResult> {
let configFile =
options.config !== undefined ? findConfiguration(options.config).results : undefined;
let formatter = options.format;
if (formatter === undefined) {
formatter =
configFile && configFile.linterOptions && configFile.linterOptions.format
? configFile.linterOptions.format
: "stylish";
}
const linter = new Linter(
{
fix: !!options.fix,
formatter,
formattersDirectory: options.formattersDirectory,
quiet: !!options.quiet,
rulesDirectory: options.rulesDirectory,
},
program,
);
let lastFolder: string | 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, configFile)) {
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 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")}`;
}