-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
lint.ts
431 lines (375 loc) · 16.1 KB
/
lint.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
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
import type { CSpellReporter, CSpellSettings, Glob, Issue, RunResult, TextDocumentOffset } from '@cspell/cspell-types';
import { MessageTypes } from '@cspell/cspell-types';
import * as commentJson from 'comment-json';
import { findRepoRoot, GitIgnore } from 'cspell-gitignore';
import { GlobMatcher, type GlobMatchOptions, type GlobPatternNormalized, type GlobPatternWithRoot } from 'cspell-glob';
import type { Logger, ValidationIssue } from 'cspell-lib';
import * as cspell from 'cspell-lib';
import * as path from 'path';
import { format } from 'util';
import { URI } from 'vscode-uri';
import {
ConfigInfo,
fileInfoToDocument,
FileResult,
findFiles,
readConfig,
readFileInfo,
readFileListFiles,
} from '../fileHelper';
import type { CSpellLintResultCache } from '../util/cache';
import { calcCacheSettings, createCache, CreateCacheSettings } from '../util/cache';
import { toApplicationError, toError } from '../util/errors';
import type { GlobOptions } from '../util/glob';
import { buildGlobMatcher, extractGlobsFromMatcher, extractPatterns, normalizeGlobsToRoot } from '../util/glob';
import { loadReporters, mergeReporters } from '../util/reporters';
import { getTimeMeasurer } from '../util/timer';
import * as util from '../util/util';
import { LintRequest } from './LintRequest';
export async function runLint(cfg: LintRequest): Promise<RunResult> {
let { reporter } = cfg;
const { fileLists } = cfg;
cspell.setLogger(getLoggerFromReporter(reporter));
const configErrors = new Set<string>();
const lintResult = await run();
await reporter.result(lintResult);
return lintResult;
async function processFile(
filename: string,
configInfo: ConfigInfo,
cache: CSpellLintResultCache
): Promise<FileResult> {
const cachedResult = await cache.getCachedLintResults(filename);
if (cachedResult) {
reporter.debug(`Filename: ${filename}, using cache`);
return cachedResult;
}
const result: FileResult = {
fileInfo: {
filename,
},
issues: [],
processed: false,
errors: 0,
configErrors: 0,
elapsedTimeMs: 0,
};
const fileInfo = await readFileInfo(filename, undefined, true);
if (fileInfo.errorCode) {
if (fileInfo.errorCode !== 'EISDIR' && cfg.options.mustFindFiles) {
const err = toError(`File not found: "${filename}"`);
reporter.error('Linter:', err);
result.errors += 1;
}
return result;
}
const doc = fileInfoToDocument(fileInfo, cfg.options.languageId, cfg.locale);
const { text } = fileInfo;
reporter.debug(`Filename: ${filename}, LanguageIds: ${doc.languageId ?? 'default'}`);
result.fileInfo = fileInfo;
const getElapsedTimeMs = getTimeMeasurer();
let spellResult: Partial<cspell.SpellCheckFileResult> = {};
reporter.info(
`Checking: ${filename}, File type: ${doc.languageId ?? 'auto'}, Language: ${doc.locale ?? 'default'}`,
MessageTypes.Info
);
try {
const validateOptions = { generateSuggestions: cfg.options.showSuggestions, numSuggestions: 5 };
const r = await cspell.spellCheckDocument(doc, validateOptions, configInfo.config);
spellResult = r;
result.processed = r.checked;
result.issues = cspell.Text.calculateTextDocumentOffsets(doc.uri, text, r.issues).map(mapIssue);
} catch (e) {
reporter.error(`Failed to process "${filename}"`, toError(e));
result.errors += 1;
}
result.elapsedTimeMs = getElapsedTimeMs();
const config = spellResult.settingsUsed ?? {};
result.configErrors += await reportConfigurationErrors(config);
const debugCfg = { config: { ...config, source: null }, source: spellResult.localConfigFilepath };
reporter.debug(commentJson.stringify(debugCfg, undefined, 2));
const elapsed = result.elapsedTimeMs / 1000.0;
const dictionaries = config.dictionaries || [];
reporter.info(
`Checked: ${filename}, File type: ${config.languageId}, Language: ${config.language} ... Issues: ${result.issues.length} ${elapsed}S`,
MessageTypes.Info
);
reporter.info(`Config file Used: ${spellResult.localConfigFilepath || configInfo.source}`, MessageTypes.Info);
reporter.info(`Dictionaries Used: ${dictionaries.join(', ')}`, MessageTypes.Info);
const dep = calcDependencies(config);
cache.setCachedLintResults(result, dep.files);
return result;
}
function mapIssue({ doc: _, ...tdo }: TextDocumentOffset & ValidationIssue): Issue {
const context = cfg.showContext
? extractContext(tdo, cfg.showContext)
: { text: tdo.line.text.trimEnd(), offset: tdo.line.offset };
return { ...tdo, context };
}
async function processFiles(
files: string[],
configInfo: ConfigInfo,
cacheSettings: CreateCacheSettings
): Promise<RunResult> {
const fileCount = files.length;
const status: RunResult = runResult();
const cache = createCache(cacheSettings);
const emitProgress = (filename: string, fileNum: number, result: FileResult) =>
reporter.progress({
type: 'ProgressFileComplete',
fileNum,
fileCount,
filename,
elapsedTimeMs: result?.elapsedTimeMs,
processed: result?.processed,
numErrors: result?.issues.length || result?.errors,
cached: result?.cached,
});
async function* loadAndProcessFiles() {
for (let i = 0; i < files.length; i++) {
const filename = files[i];
const result = await processFile(filename, configInfo, cache);
yield { filename, fileNum: i + 1, result };
}
}
for await (const fileP of loadAndProcessFiles()) {
const { filename, fileNum, result } = await fileP;
status.files += 1;
status.cachedFiles = (status.cachedFiles || 0) + (result.cached ? 1 : 0);
emitProgress(filename, fileNum, result);
// Show the spelling errors after emitting the progress.
result.issues.filter(cfg.uniqueFilter).forEach((issue) => reporter.issue(issue));
if (result.issues.length || result.errors) {
status.filesWithIssues.add(filename);
status.issues += result.issues.length;
status.errors += result.errors;
}
status.errors += result.configErrors;
}
cache.reconcile();
return status;
}
interface ConfigDependencies {
files: string[];
}
function calcDependencies(config: CSpellSettings): ConfigDependencies {
const { configFiles, dictionaryFiles } = cspell.extractDependencies(config);
return { files: configFiles.concat(dictionaryFiles) };
}
async function reportConfigurationErrors(config: CSpellSettings): Promise<number> {
const errors = cspell.extractImportErrors(config);
let count = 0;
errors.forEach((ref) => {
const key = ref.error.toString();
if (configErrors.has(key)) return;
configErrors.add(key);
count += 1;
reporter.error('Configuration', ref.error);
});
const dictCollection = await cspell.getDictionary(config);
dictCollection.dictionaries.forEach((dict) => {
const dictErrors = dict.getErrors?.() || [];
const msg = `Dictionary Error with (${dict.name})`;
dictErrors.forEach((error) => {
const key = msg + error.toString();
if (configErrors.has(key)) return;
configErrors.add(key);
count += 1;
reporter.error(msg, error);
});
});
return count;
}
function countConfigErrors(configInfo: ConfigInfo): Promise<number> {
return reportConfigurationErrors(configInfo.config);
}
async function run(): Promise<RunResult> {
if (cfg.options.root) {
process.env[cspell.ENV_CSPELL_GLOB_ROOT] = cfg.root;
}
const configInfo: ConfigInfo = await readConfig(cfg.configFile, cfg.root);
reporter = mergeReporters(cfg.reporter, ...loadReporters(configInfo.config));
cspell.setLogger(getLoggerFromReporter(reporter));
const useGitignore = cfg.options.gitignore ?? configInfo.config.useGitignore ?? false;
const gitignoreRoots = cfg.options.gitignoreRoot ?? configInfo.config.gitignoreRoot;
const gitIgnore = useGitignore ? await generateGitIgnore(gitignoreRoots) : undefined;
const cliGlobs: Glob[] = cfg.fileGlobs;
const allGlobs: Glob[] = cliGlobs.length ? cliGlobs : configInfo.config.files || [];
const combinedGlobs = normalizeGlobsToRoot(allGlobs, cfg.root, false);
const cliExcludeGlobs = extractPatterns(cfg.excludes).map((p) => p.glob);
const normalizedExcludes = normalizeGlobsToRoot(cliExcludeGlobs, cfg.root, true);
const includeGlobs = combinedGlobs.filter((g) => !g.startsWith('!'));
const excludeGlobs = combinedGlobs.filter((g) => g.startsWith('!')).concat(normalizedExcludes);
const fileGlobs: string[] = includeGlobs;
const hasFileLists = !!fileLists.length;
if (!fileGlobs.length && !hasFileLists) {
// Nothing to do.
return runResult();
}
header(fileGlobs, excludeGlobs);
reporter.info(`Config Files Found:\n ${configInfo.source}\n`, MessageTypes.Info);
const configErrors = await countConfigErrors(configInfo);
if (configErrors) return runResult({ errors: configErrors });
// Get Exclusions from the config files.
const { root } = cfg;
const globsToExclude = (configInfo.config.ignorePaths || []).concat(excludeGlobs);
const globMatcher = buildGlobMatcher(globsToExclude, root, true);
const ignoreGlobs = extractGlobsFromMatcher(globMatcher);
// cspell:word nodir
const globOptions: GlobOptions = {
root,
cwd: root,
ignore: ignoreGlobs.concat(normalizedExcludes),
nodir: true,
};
const enableGlobDot = cfg.enableGlobDot ?? configInfo.config.enableGlobDot;
if (enableGlobDot !== undefined) {
globOptions.dot = enableGlobDot;
}
try {
const cacheSettings = await calcCacheSettings(configInfo.config, cfg.options, root);
const foundFiles = await (hasFileLists
? useFileLists(fileLists, allGlobs, root, enableGlobDot)
: findFiles(fileGlobs, globOptions));
const filtered = gitIgnore ? await gitIgnore.filterOutIgnored(foundFiles) : foundFiles;
const files = filterFiles(filtered, globMatcher);
return await processFiles(files, configInfo, cacheSettings);
} catch (e) {
const err = toApplicationError(e);
reporter.error('Linter', err);
return runResult({ errors: 1 });
}
}
function header(files: string[], cliExcludes: string[]) {
const formattedFiles = files.length > 100 ? files.slice(0, 100).concat(['...']) : files;
reporter.info(
`
cspell;
Date: ${new Date().toUTCString()}
Options:
verbose: ${yesNo(!!cfg.options.verbose)}
config: ${cfg.configFile || 'default'}
exclude: ${cliExcludes.join('\n ')}
files: ${formattedFiles}
wordsOnly: ${yesNo(!!cfg.options.wordsOnly)}
unique: ${yesNo(!!cfg.options.unique)}
`,
MessageTypes.Info
);
}
function isExcluded(filename: string, globMatcherExclude: GlobMatcher) {
if (cspell.isBinaryFile(URI.file(filename))) {
return true;
}
const { root } = cfg;
const absFilename = path.resolve(root, filename);
const r = globMatcherExclude.matchEx(absFilename);
if (r.matched) {
const { glob, source } = extractGlobSource(r.pattern);
reporter.info(
`Excluded File: ${path.relative(root, absFilename)}; Excluded by ${glob} from ${source}`,
MessageTypes.Info
);
}
return r.matched;
}
function extractGlobSource(g: GlobPatternWithRoot | GlobPatternNormalized) {
const { glob, rawGlob, source } = <GlobPatternNormalized>g;
return {
glob: rawGlob || glob,
source,
};
}
function filterFiles(files: string[], globMatcherExclude: GlobMatcher): string[] {
const patterns = globMatcherExclude.patterns;
const excludeInfo = patterns
.map(extractGlobSource)
.map(({ glob, source }) => `Glob: ${glob} from ${source}`)
.filter(util.uniqueFn());
reporter.info(`Exclusion Globs: \n ${excludeInfo.join('\n ')}\n`, MessageTypes.Info);
const result = files.filter(util.uniqueFn()).filter((filename) => !isExcluded(filename, globMatcherExclude));
return result;
}
}
function extractContext(
tdo: Pick<cspell.TextDocumentOffset, 'line' | 'offset' | 'text'>,
contextRange: number
): cspell.TextOffset {
const { line, offset } = tdo;
const textOffsetInLine = offset - line.offset;
let left = Math.max(textOffsetInLine - contextRange, 0);
let right = Math.min(line.text.length, textOffsetInLine + contextRange + tdo.text.length);
const lineText = line.text;
const isLetter = /^[a-z]$/i;
const isSpace = /^\s$/;
for (let n = contextRange / 2; n > 0 && left > 0; n--, left--) {
if (!isLetter.test(lineText[left - 1])) {
break;
}
}
for (let n = contextRange / 2; n > 0 && right < lineText.length; n--, right++) {
if (!isLetter.test(lineText[right])) {
break;
}
}
// remove leading space
for (; left < textOffsetInLine && isSpace.test(lineText[left]); left++) {
/* do nothing */
}
const context = {
text: line.text.slice(left, right).trimEnd(),
offset: left + line.offset,
};
return context;
}
function runResult(init: Partial<RunResult> = {}): RunResult {
const { files = 0, filesWithIssues = new Set<string>(), issues = 0, errors = 0, cachedFiles = 0 } = init;
return { files, filesWithIssues, issues, errors, cachedFiles };
}
function yesNo(value: boolean) {
return value ? 'Yes' : 'No';
}
function getLoggerFromReporter(reporter: CSpellReporter): Logger {
const log: Logger['log'] = (...params) => {
const msg = format(...params);
reporter.info(msg, 'Info');
};
const error: Logger['error'] = (...params) => {
const msg = format(...params);
const err = { message: '', name: 'error', toString: () => '' };
reporter.error(msg, err);
};
const warn: Logger['warn'] = (...params) => {
const msg = format(...params);
reporter.info(msg, 'Warning');
};
return {
log,
warn,
error,
};
}
async function generateGitIgnore(roots: string | string[] | undefined) {
const root = (typeof roots === 'string' ? [roots].filter((r) => !!r) : roots) || [];
if (!root?.length) {
const cwd = process.cwd();
const repo = (await findRepoRoot(cwd)) || cwd;
root.push(repo);
}
return new GitIgnore(root?.map((p) => path.resolve(p)));
}
async function useFileLists(
fileListFiles: string[],
includeGlobPatterns: Glob[],
root: string,
dot: boolean | undefined
): Promise<string[]> {
includeGlobPatterns = includeGlobPatterns.length ? includeGlobPatterns : ['**'];
const options: GlobMatchOptions = { root, mode: 'include' };
if (dot !== undefined) {
options.dot = dot;
}
const globMatcher = new GlobMatcher(includeGlobPatterns, options);
const files = await readFileListFiles(fileListFiles);
return files.filter((file) => globMatcher.match(file));
}