-
-
Notifications
You must be signed in to change notification settings - Fork 237
/
IncrementalChecker.ts
352 lines (302 loc) · 9.68 KB
/
IncrementalChecker.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
342
343
344
345
346
347
348
349
350
351
352
import * as fs from 'fs';
import endsWith = require('lodash/endsWith');
import * as path from 'path';
import * as ts from 'typescript';
import { Configuration, Linter } from 'tslint'; // Imported for types alone; actual requires take place in methods below
import { FilesRegister } from './FilesRegister';
import { FilesWatcher } from './FilesWatcher';
import { WorkSet } from './WorkSet';
import { NormalizedMessage } from './NormalizedMessage';
import { CancellationToken } from './CancellationToken';
import * as minimatch from 'minimatch';
import { VueProgram } from './VueProgram';
// Need some augmentation here - linterOptions.exclude is not (yet) part of the official
// types for tslint.
interface ConfigurationFile extends Configuration.IConfigurationFile {
linterOptions?: {
typeCheck?: boolean;
exclude?: string[];
};
}
export class IncrementalChecker {
programConfigFile: string;
compilerOptions: object;
linterConfigFile: string | false;
linterAutoFix: boolean;
watchPaths: string[];
workNumber: number;
workDivision: number;
checkSyntacticErrors: boolean;
files: FilesRegister;
linter: Linter;
linterConfig: ConfigurationFile;
linterExclusions: minimatch.IMinimatch[];
program: ts.Program;
programConfig: ts.ParsedCommandLine;
watcher: FilesWatcher;
vue: boolean;
constructor(
programConfigFile: string,
compilerOptions: object,
linterConfigFile: string | false,
linterAutoFix: boolean,
watchPaths: string[],
workNumber: number,
workDivision: number,
checkSyntacticErrors: boolean,
vue: boolean
) {
this.programConfigFile = programConfigFile;
this.compilerOptions = compilerOptions;
this.linterConfigFile = linterConfigFile;
this.linterAutoFix = linterAutoFix;
this.watchPaths = watchPaths;
this.workNumber = workNumber || 0;
this.workDivision = workDivision || 1;
this.checkSyntacticErrors = checkSyntacticErrors || false;
this.vue = vue || false;
// Use empty array of exclusions in general to avoid having
// to check of its existence later on.
this.linterExclusions = [];
// it's shared between compilations
this.files = new FilesRegister(() => ({
// data shape
source: undefined,
linted: false,
lints: []
}));
}
static loadProgramConfig(configFile: string, compilerOptions: object) {
const tsconfig = ts.readConfigFile(configFile, ts.sys.readFile).config;
tsconfig.compilerOptions = tsconfig.compilerOptions || {};
tsconfig.compilerOptions = {
...tsconfig.compilerOptions,
...compilerOptions
};
const parsed = ts.parseJsonConfigFileContent(
tsconfig,
ts.sys,
path.dirname(configFile)
);
return parsed;
}
static loadLinterConfig(configFile: string): ConfigurationFile {
const tslint = require('tslint');
return tslint.Configuration.loadConfigurationFromPath(
configFile
) as ConfigurationFile;
}
static createProgram(
programConfig: ts.ParsedCommandLine,
files: FilesRegister,
watcher: FilesWatcher,
oldProgram: ts.Program
) {
const host = ts.createCompilerHost(programConfig.options);
const realGetSourceFile = host.getSourceFile;
host.getSourceFile = (filePath, languageVersion, onError) => {
// first check if watcher is watching file - if not - check it's mtime
if (!watcher.isWatchingFile(filePath)) {
try {
const stats = fs.statSync(filePath);
files.setMtime(filePath, stats.mtime.valueOf());
} catch (e) {
// probably file does not exists
files.remove(filePath);
}
}
// get source file only if there is no source in files register
if (!files.has(filePath) || !files.getData(filePath).source) {
files.mutateData(filePath, data => {
data.source = realGetSourceFile(filePath, languageVersion, onError);
});
}
return files.getData(filePath).source;
};
return ts.createProgram(
programConfig.fileNames,
programConfig.options,
host,
oldProgram // re-use old program
);
}
createLinter(program: ts.Program) {
const tslint = require('tslint');
return new tslint.Linter({ fix: this.linterAutoFix }, program);
}
static isFileExcluded(
filePath: string,
linterExclusions: minimatch.IMinimatch[]
): boolean {
return (
endsWith(filePath, '.d.ts') ||
linterExclusions.some(matcher => matcher.match(filePath))
);
}
nextIteration() {
if (!this.watcher) {
const watchExtensions = this.vue
? ['.ts', '.tsx', '.vue']
: ['.ts', '.tsx'];
this.watcher = new FilesWatcher(this.watchPaths, watchExtensions);
// connect watcher with register
this.watcher.on('change', (filePath: string, stats: fs.Stats) => {
this.files.setMtime(filePath, stats.mtime.valueOf());
});
this.watcher.on('unlink', (filePath: string) => {
this.files.remove(filePath);
});
this.watcher.watch();
}
if (!this.linterConfig && this.linterConfigFile) {
this.linterConfig = IncrementalChecker.loadLinterConfig(
this.linterConfigFile
);
if (
this.linterConfig.linterOptions &&
this.linterConfig.linterOptions.exclude
) {
// Pre-build minimatch patterns to avoid additional overhead later on.
// Note: Resolving the path is required to properly match against the full file paths,
// and also deals with potential cross-platform problems regarding path separators.
this.linterExclusions = this.linterConfig.linterOptions.exclude.map(
pattern => new minimatch.Minimatch(path.resolve(pattern))
);
}
}
this.program = this.vue ? this.loadVueProgram() : this.loadDefaultProgram();
if (this.linterConfig) {
this.linter = this.createLinter(this.program);
}
}
loadVueProgram() {
this.programConfig =
this.programConfig ||
VueProgram.loadProgramConfig(
this.programConfigFile,
this.compilerOptions
);
return VueProgram.createProgram(
this.programConfig,
path.dirname(this.programConfigFile),
this.files,
this.watcher,
this.program
);
}
loadDefaultProgram() {
this.programConfig =
this.programConfig ||
IncrementalChecker.loadProgramConfig(
this.programConfigFile,
this.compilerOptions
);
return IncrementalChecker.createProgram(
this.programConfig,
this.files,
this.watcher,
this.program
);
}
hasLinter() {
return this.linter !== undefined;
}
getDiagnostics(cancellationToken: CancellationToken) {
const diagnostics: ts.Diagnostic[] = [];
// select files to check (it's semantic check - we have to include all files :/)
const filesToCheck = this.program.getSourceFiles();
// calculate subset of work to do
const workSet = new WorkSet(
filesToCheck,
this.workNumber,
this.workDivision
);
// check given work set
workSet.forEach(sourceFile => {
if (cancellationToken) {
cancellationToken.throwIfCancellationRequested();
}
const diagnosticsToRegister: ReadonlyArray<ts.Diagnostic> = this
.checkSyntacticErrors
? []
.concat(
this.program.getSemanticDiagnostics(sourceFile, cancellationToken)
)
.concat(
this.program.getSyntacticDiagnostics(
sourceFile,
cancellationToken
)
)
: this.program.getSemanticDiagnostics(sourceFile, cancellationToken);
diagnostics.push.apply(diagnostics, diagnosticsToRegister);
});
// normalize and deduplicate diagnostics
return NormalizedMessage.deduplicate(
diagnostics.map(NormalizedMessage.createFromDiagnostic)
);
}
getLints(cancellationToken: CancellationToken) {
if (!this.hasLinter()) {
throw new Error('Cannot get lints - checker has no linter.');
}
// select files to lint
const filesToLint = this.files
.keys()
.filter(
filePath =>
!this.files.getData(filePath).linted &&
!IncrementalChecker.isFileExcluded(filePath, this.linterExclusions)
);
// calculate subset of work to do
const workSet = new WorkSet(
filesToLint,
this.workNumber,
this.workDivision
);
// lint given work set
workSet.forEach(fileName => {
cancellationToken.throwIfCancellationRequested();
try {
this.linter.lint(fileName, undefined, this.linterConfig);
} catch (e) {
if (
fs.existsSync(fileName) &&
// check the error type due to file system lag
!(e instanceof Error) &&
!(e.constructor.name === 'FatalError') &&
!(e.message && e.message.trim().startsWith('Invalid source file'))
) {
// it's not because file doesn't exist - throw error
throw e;
}
}
});
// set lints in files register
this.linter.getResult().failures.forEach(lint => {
const filePath = lint.getFileName();
this.files.mutateData(filePath, data => {
data.linted = true;
data.lints.push(lint);
});
});
// set all files as linted
this.files.keys().forEach(filePath => {
this.files.mutateData(filePath, data => {
data.linted = true;
});
});
// get all lints
const lints = this.files
.keys()
.reduce(
(innerLints, filePath) =>
innerLints.concat(this.files.getData(filePath).lints),
[]
);
// normalize and deduplicate lints
return NormalizedMessage.deduplicate(
lints.map(NormalizedMessage.createFromLint)
);
}
}