-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
app.ts
414 lines (378 loc) · 16.7 KB
/
app.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
import * as path from 'path';
import * as commander from 'commander';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const npmPackage = require(path.join(__dirname, '..', 'package.json'));
import { checkText } from './application';
import { CSpellApplicationOptions, BaseOptions, TraceOptions } from './options';
import * as App from './application';
import chalk = require('chalk');
import {
addPathsToGlobalImports,
addPathsToGlobalImportsResultToTable,
listGlobalImports,
listGlobalImportsResultToTable,
removePathsFromGlobalImports,
} from './link';
import { tableToLines } from './util/table';
import { Emitters, isProgressFileComplete, MessageType, ProgressItem, Issue } from './emitters';
import { isSpellingDictionaryLoadError, SpellingDictionaryLoadError, ImportError } from 'cspell-lib';
import { emitTraceResults } from './traceEmitter';
import { CheckFailed } from './util/errors';
export { CheckFailed } from './util/errors';
interface Options extends CSpellApplicationOptions {
legacy?: boolean;
summary: boolean;
issues: boolean;
silent: boolean;
mustFindFiles: boolean;
progress?: boolean;
/**
* issues are shown with a relative path to the root or `cwd`
*/
relative?: boolean;
}
// interface InitOptions extends Options {}
const templateIssue = `{green $uri}:{yellow $row:$col} - $message ({red $text})`;
const templateIssueWithSuggestions = `{green $uri}:{yellow $row:$col} - $message ({red $text}) Suggestions: {yellow [$suggestions]}`;
const templateIssueWithContext = `{green $uri}:{yellow $row:$col} $padRowCol- $message ({red $text})$padContext -- {gray $contextLeft}{red {underline $text}}{gray $contextRight}`;
const templateIssueWithContextWithSuggestions = `{green $uri}:{yellow $row:$col} $padRowCol- $message ({red $text})$padContext -- {gray $contextLeft}{red {underline $text}}{gray $contextRight}\n\t Suggestions: {yellow [$suggestions]}`;
const templateIssueLegacy = `${chalk.green('$uri')}[$row, $col]: $message: ${chalk.red('$text')}`;
const templateIssueWordsOnly = '$text';
function genIssueEmitter(template: string) {
const defaultWidth = 10;
let maxWidth = defaultWidth;
let uri: string | undefined;
return function issueEmitter(issue: Issue) {
if (uri !== issue.uri) {
maxWidth = defaultWidth;
uri = issue.uri;
}
maxWidth = Math.max(maxWidth * 0.999, issue.text.length, 10);
console.log(formatIssue(template, issue, Math.ceil(maxWidth)));
};
}
function errorEmitter(message: string, error: Error | SpellingDictionaryLoadError | ImportError) {
if (isSpellingDictionaryLoadError(error)) {
error = error.cause;
}
console.error(chalk.red(message), error.toString());
}
type InfoEmitter = Record<MessageType, (msg: string) => void>;
function nullEmitter() {
/* empty */
}
function relativeFilename(filename: string, cwd = process.cwd()): string {
const rel = path.relative(cwd, filename);
if (rel.startsWith('..')) return filename;
return '.' + path.sep + rel;
}
function reportProgress(p: ProgressItem) {
if (isProgressFileComplete(p)) {
const fc = '' + p.fileCount;
const fn = (' '.repeat(fc.length) + p.fileNum).slice(-fc.length);
const idx = fn + '/' + fc;
const filename = chalk.gray(relativeFilename(p.filename));
const time = reportTime(p.elapsedTimeMs);
const skipped = p.processed === false ? ' skipped' : '';
const hasErrors = p.numErrors ? chalk.red` X` : '';
console.error(`${idx} ${filename} ${time}${skipped}${hasErrors}`);
}
}
function reportTime(elapsedTimeMs: number | undefined): string {
if (elapsedTimeMs === undefined) return '-';
const color = elapsedTimeMs < 1000 ? chalk.white : elapsedTimeMs < 2000 ? chalk.yellow : chalk.redBright;
return color(elapsedTimeMs.toFixed(2) + 'ms');
}
function getEmitters(options: Options): Emitters {
const issueTemplate = options.wordsOnly
? templateIssueWordsOnly
: options.legacy
? templateIssueLegacy
: options.showContext
? options.showSuggestions
? templateIssueWithContextWithSuggestions
: templateIssueWithContext
: options.showSuggestions
? templateIssueWithSuggestions
: templateIssue;
const { silent, issues, progress, verbose, debug } = options;
const emitters: InfoEmitter = {
Debug: !silent && debug ? (s) => console.info(chalk.cyan(s)) : nullEmitter,
Info: !silent && verbose ? (s) => console.info(chalk.yellow(s)) : nullEmitter,
Warning: (s) => console.info(chalk.yellow(s)),
};
function infoEmitter(message: string, msgType: MessageType): void {
emitters[msgType]?.(message);
}
const root = options.root || process.cwd();
function relativeIssue(fn: (i: Issue) => void): (i: Issue) => void {
if (!options.relative) return fn;
return (i: Issue) => {
const r = { ...i };
r.uri = r.uri ? relativeFilename(r.uri, root) : r.uri;
fn(r);
};
}
return {
issue: relativeIssue(silent || !issues ? nullEmitter : genIssueEmitter(issueTemplate)),
error: silent ? nullEmitter : errorEmitter,
info: infoEmitter,
debug: emitters.Debug,
progress: !silent && progress ? reportProgress : nullEmitter,
};
}
export async function run(program?: commander.Command, argv?: string[]): Promise<void> {
const prog = program || commander.program;
const args = argv || process.argv;
prog.exitOverride();
prog.version(npmPackage.version)
.description('Spelling Checker for Code')
.name('cspell')
.option('--no-color', 'Turn off color.')
.option('--color', 'Force color');
const spellCheckCommand = prog.command('lint', { isDefault: true });
spellCheckCommand
.description('Check spelling')
.option(
'-c, --config <cspell.json>',
'Configuration file to use. By default cspell looks for cspell.json in the current directory.'
)
.option('-v, --verbose', 'display more information about the files being checked and the configuration')
.option(
'--locale <locale>',
'Set language locales. i.e. "en,fr" for English and French, or "en-GB" for British English.'
)
.option('--language-id <language>', 'Force programming language for unknown extensions. i.e. "php" or "scala"')
.option('--languageId <language>', 'Force programming language for unknown extensions. i.e. "php" or "scala"')
.option('--wordsOnly', 'Only output the words not found in the dictionaries.')
.option('-u, --unique', 'Only output the first instance of a word not found in the dictionaries.')
.option('--debug', 'Output information useful for debugging cspell.json files.')
.option(
'-e, --exclude <glob>',
'Exclude files matching the glob pattern. This option can be used multiple times to add multiple globs. ',
collect
)
.option('--no-issues', 'Do not show the spelling errors.')
.option('--no-progress', 'Turn off progress messages')
.option('--no-summary', 'Turn off summary message in console')
.option('-s, --silent', 'Silent mode, suppress error messages')
.option('-r, --root <root folder>', 'Root directory, defaults to current directory.')
.option('--relative', 'Issues are displayed relative to root.')
.option('--show-context', 'Show the surrounding text around an issue.')
.option('--show-suggestions', 'Show spelling suggestions.')
.option('--must-find-files', 'Error if no files are found', true)
.option('--no-must-find-files', 'Do not error if no files are found')
// The following options are planned features
// .option('-w, --watch', 'Watch for any changes to the matching files and report any errors')
// .option('--force', 'Force the exit value to always be 0')
.option('--legacy', 'Legacy output')
.option('--local <local>', 'Deprecated -- Use: --locale')
.addHelpText('after', usage)
.arguments('[files...]')
.action((files: string[], options: Options) => {
const { mustFindFiles } = options;
const emitters: Emitters = getEmitters(options);
return App.lint(files, options, emitters).then((result) => {
if (!files.length && !result.files) {
spellCheckCommand.outputHelp();
throw new CheckFailed('outputHelp', 1);
}
if (options.summary && !options.silent) {
console.error(
'CSpell: Files checked: %d, Issues found: %d in %d files',
result.files,
result.issues,
result.filesWithIssues.size
);
}
if (result.issues || result.errors || (mustFindFiles && !result.files)) {
throw new CheckFailed('check failed', 1);
}
return;
});
});
type TraceCommandOptions = TraceOptions;
prog.command('trace')
.description(
`Trace words
Search for words in the configuration and dictionaries.`
)
.option(
'-c, --config <cspell.json>',
'Configuration file to use. By default cspell looks for cspell.json in the current directory.'
)
.option(
'--locale <locale>',
'Set language locales. i.e. "en,fr" for English and French, or "en-GB" for British English.'
)
.option('--languageId <language>', 'Force programming language for unknown extensions. i.e. "php" or "scala"')
.option('--no-color', 'Turn off color.')
.option('--color', 'Force color')
.arguments('<words...>')
.action(async (words: string[], options: TraceCommandOptions) => {
const results = await App.trace(words, options);
emitTraceResults(results, { cwd: process.cwd() });
const numFound = results.reduce((n, r) => n + (r.found ? 1 : 0), 0);
if (!numFound) {
console.error('No matches found');
throw new CheckFailed('no matches', 1);
}
const numErrors = results.map((r) => r.errors?.length || 0).reduce((n, r) => n + r, 0);
if (numErrors) {
console.error('Dictionary Errors.');
throw new CheckFailed('dictionary errors', 1);
}
});
type CheckCommandOptions = BaseOptions;
prog.command('check <files...>')
.description('Spell check file(s) and display the result. The full file is displayed in color.')
.option(
'-c, --config <cspell.json>',
'Configuration file to use. By default cspell looks for cspell.json in the current directory.'
)
.option('--no-color', 'Turn off color.')
.option('--color', 'Force color')
.action(async (files: string[], options: CheckCommandOptions) => {
let issueCount = 0;
for (const filename of files) {
console.log(chalk.yellowBright(`Check file: ${filename}`));
console.log();
try {
const result = await checkText(filename, options);
for (const item of result.items) {
const fn =
item.flagIE === App.IncludeExcludeFlag.EXCLUDE
? chalk.gray
: item.isError
? chalk.red
: chalk.whiteBright;
const t = fn(item.text);
process.stdout.write(t);
issueCount += item.isError ? 1 : 0;
}
console.log();
} catch (e) {
console.error(`File not found "${filename}"`);
throw new CheckFailed('File not found', 1);
}
console.log();
}
if (issueCount) {
throw new CheckFailed('Issues found', 1);
}
});
const linkCommand = prog
.command('link')
.description('Link dictionaries any other settings to the cspell global config.');
linkCommand
.command('list', { isDefault: true })
.alias('ls')
.description('List currently linked configurations.')
.action(() => {
const imports = listGlobalImports();
const table = listGlobalImportsResultToTable(imports.list);
tableToLines(table).forEach((line) => console.log(line));
return;
});
linkCommand
.command('add <dictionaries...>')
.alias('a')
.description('Add dictionaries any other settings to the cspell global config.')
.action((dictionaries: string[]) => {
const r = addPathsToGlobalImports(dictionaries);
const table = addPathsToGlobalImportsResultToTable(r);
console.log('Adding:');
tableToLines(table).forEach((line) => console.log(line));
if (r.error) {
throw new CheckFailed(r.error, 1);
}
return;
});
linkCommand
.command('remove <paths...>')
.alias('r')
.description('Remove matching paths / packages from the global config.')
.action((dictionaries: string[]) => {
const r = removePathsFromGlobalImports(dictionaries);
console.log('Removing:');
if (r.error) {
throw new CheckFailed(r.error, 1);
}
r.removed.map((f) => console.log(f));
return;
});
/*
program
.command('init')
.description('(Alpha) Initialize a cspell.json file.')
.option('-o, --output <cspell.json>', 'define where to write file.')
.option('--extends <cspell.json>', 'extend an existing cspell.json file.')
.action((options: InitOptions) => {
showHelp = false;
CSpellApplication.createInit(options).then(
() => process.exit(0),
() => process.exit(1)
);
console.log('Init');
});
*/
return prog.parseAsync(args).then(() => {
return;
});
}
const usage = `
Examples:
cspell "*.js" Check all .js files in the current directory
cspell "**/*.js" Check all .js files from the current directory
cspell "src/**/*.js" Only check .js under src
cspell "**/*.txt" "**/*.js" Check both .js and .txt files.
cspell "**/*.{txt,js,md}" Check .txt, .js, and .md files.
cat LICENSE | cspell stdin Check stdin
`;
function collect(value: string, previous: string[] | undefined): string[] {
if (!previous) {
return [value];
}
return previous.concat([value]);
}
function formatIssue(templateStr: string, issue: Issue, maxIssueTextWidth: number) {
function clean(t: string) {
return t.replace(/\s+/, ' ');
}
const { uri = '', row, col, text, context, offset } = issue;
const contextLeft = clean(context.text.slice(0, offset - context.offset));
const contextRight = clean(context.text.slice(offset + text.length - context.offset));
const contextFull = clean(context.text);
const padContext = ' '.repeat(Math.max(maxIssueTextWidth - text.length, 0));
const rowText = row.toString();
const colText = col.toString();
const padRowCol = ' '.repeat(Math.max(1, 8 - (rowText.length + colText.length)));
const suggestions = issue.suggestions?.join(', ') || '';
const message = issue.isFlagged ? '{yellow Forbidden word}' : 'Unknown word';
const t = template(templateStr.replace(/\$message/g, message));
return chalk(t)
.replace(/\$\{col\}/g, colText)
.replace(/\$\{row\}/g, rowText)
.replace(/\$\{text\}/g, text)
.replace(/\$\{uri\}/g, uri)
.replace(/\$col/g, colText)
.replace(/\$contextFull/g, contextFull)
.replace(/\$contextLeft/g, contextLeft)
.replace(/\$contextRight/g, contextRight)
.replace(/\$padContext/g, padContext)
.replace(/\$padRowCol/g, padRowCol)
.replace(/\$row/g, rowText)
.replace(/\$suggestions/g, suggestions)
.replace(/\$text/g, text)
.replace(/\$uri/g, uri);
}
class TS extends Array<string> {
raw: string[];
constructor(s: string) {
super(s);
this.raw = [s];
}
}
function template(s: string): TemplateStringsArray {
return new TS(s);
}