/
cli-reporter.ts
275 lines (241 loc) · 9.08 KB
/
cli-reporter.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
import chalk = require('chalk');
import type {
CSpellReporter,
Issue,
MessageType,
ProgressFileBegin,
ProgressFileComplete,
ProgressItem,
RunResult,
} from '@cspell/cspell-types';
import { ImportError, isSpellingDictionaryLoadError, SpellingDictionaryLoadError } from 'cspell-lib';
import * as path from 'path';
import { URI } from 'vscode-uri';
import { LinterCliOptions } from './options';
const templateIssue = `{green $filename}:{yellow $row:$col} - $message ({red $text})`;
const templateIssueWithSuggestions = `{green $filename}:{yellow $row:$col} - $message ({red $text}) Suggestions: {yellow [$suggestions]}`;
const templateIssueWithContext = `{green $filename}:{yellow $row:$col} $padRowCol- $message ({red $text})$padContext -- {gray $contextLeft}{red {underline $text}}{gray $contextRight}`;
const templateIssueWithContextWithSuggestions = `{green $filename}:{yellow $row:$col} $padRowCol- $message ({red $text})$padContext -- {gray $contextLeft}{red {underline $text}}{gray $contextRight}\n\t Suggestions: {yellow [$suggestions]}`;
const templateIssueLegacy = `${chalk.green('$filename')}[$row, $col]: $message: ${chalk.red('$text')}`;
const templateIssueWordsOnly = '$text';
export // Exported for testing.
interface ReporterIssue extends Issue {
filename: string;
}
function genIssueEmitter(template: string) {
const defaultWidth = 10;
let maxWidth = defaultWidth;
let uri: string | undefined;
return function issueEmitter(issue: ReporterIssue) {
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 relativeUriFilename(uri: string, fsPathRoot: string): string {
const fsPath = URI.parse(uri).fsPath;
const rel = path.relative(fsPathRoot, fsPath);
if (rel.startsWith('..')) return fsPath;
return '.' + path.sep + rel;
}
function reportProgress(p: ProgressItem) {
if (p.type === 'ProgressFileComplete') {
return reportProgressFileComplete(p);
}
if (p.type === 'ProgressFileBegin') {
return reportProgressFileBegin(p);
}
}
function reportProgressFileBegin(p: ProgressFileBegin) {
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));
process.stderr.write(`\r${idx} ${filename}`);
}
function reportProgressFileComplete(p: ProgressFileComplete) {
const time = reportTime(p.elapsedTimeMs, !!p.cached);
const skipped = p.processed === false ? ' skipped' : '';
const hasErrors = p.numErrors ? chalk.red` X` : '';
console.error(` ${time}${skipped}${hasErrors}`);
}
function reportTime(elapsedTimeMs: number | undefined, cached: boolean): string {
if (cached) return chalk.green('cached');
if (elapsedTimeMs === undefined) return '-';
const color = elapsedTimeMs < 1000 ? chalk.white : elapsedTimeMs < 2000 ? chalk.yellow : chalk.redBright;
return color(elapsedTimeMs.toFixed(2) + 'ms');
}
export interface ReporterOptions
extends Pick<
LinterCliOptions,
| 'debug'
| 'issues'
| 'legacy'
| 'progress'
| 'relative'
| 'root'
| 'showContext'
| 'showSuggestions'
| 'silent'
| 'summary'
| 'verbose'
| 'wordsOnly'
> {
fileGlobs: string[];
}
export function getReporter(options: ReporterOptions): CSpellReporter {
const issueTemplate = options.wordsOnly
? templateIssueWordsOnly
: options.legacy
? templateIssueLegacy
: options.showContext
? options.showSuggestions
? templateIssueWithContextWithSuggestions
: templateIssueWithContext
: options.showSuggestions
? templateIssueWithSuggestions
: templateIssue;
const { fileGlobs, silent, summary, 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 = URI.file(options.root || process.cwd());
const fsPathRoot = root.fsPath;
function relativeIssue(fn: (i: ReporterIssue) => void): (i: Issue) => void {
const fnFilename = options.relative
? (uri: string) => relativeUriFilename(uri, fsPathRoot)
: (uri: string) => URI.parse(uri).fsPath;
return (i: Issue) => {
const filename = i.uri ? fnFilename(i.uri) : '';
const r = { ...i, filename };
fn(r);
};
}
const resultEmitter = (result: RunResult) => {
if (!fileGlobs.length && !result.files) {
return;
}
if (result.cachedFiles) {
console.error(
'CSpell: Files checked: %d (%d from cache), Issues found: %d in %d files',
result.files,
result.cachedFiles,
result.issues,
result.filesWithIssues.size
);
return;
}
console.error(
'CSpell: Files checked: %d, Issues found: %d in %d files',
result.files,
result.issues,
result.filesWithIssues.size
);
};
return {
issue: relativeIssue(silent || !issues ? nullEmitter : genIssueEmitter(issueTemplate)),
error: silent ? nullEmitter : errorEmitter,
info: infoEmitter,
debug: emitters.Debug,
progress: !silent && progress ? reportProgress : nullEmitter,
result: !silent && summary ? resultEmitter : nullEmitter,
};
}
function formatIssue(templateStr: string, issue: ReporterIssue, maxIssueTextWidth: number): string {
function clean(t: string) {
return t.replace(/\s+/, ' ');
}
const { uri = '', filename, 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 = formatSuggestions(issue);
const msg = issue.message || (issue.isFlagged ? 'Forbidden word' : 'Unknown word');
const message = issue.isFlagged ? `{yellow ${msg}}` : msg;
const substitutions = {
$col: colText,
$contextFull: contextFull,
$contextLeft: contextLeft,
$contextRight: contextRight,
$filename: filename,
$padContext: padContext,
$padRowCol: padRowCol,
$row: rowText,
$suggestions: suggestions,
$text: text,
$uri: uri,
};
const t = template(templateStr.replace(/\$message/g, message));
return substitute(chalk(t), substitutions);
}
function formatSuggestions(issue: Issue): string {
if (issue.suggestionsEx) {
return issue.suggestionsEx
.map((sug) => (sug.isPreferred ? chalk.italic(chalk.bold(sug.word)) + '*' : sug.word))
.join(', ');
}
if (issue.suggestions) {
return issue.suggestions.join(', ');
}
return '';
}
class TS extends Array<string> {
raw: string[];
constructor(s: string) {
super(s);
this.raw = [s];
}
}
function template(s: string): TemplateStringsArray {
return new TS(s);
}
function substitute(text: string, substitutions: Record<string, string>): string {
type SubRange = [number, number, string];
const subs: SubRange[] = [];
for (const [match, replaceWith] of Object.entries(substitutions)) {
const len = match.length;
for (let i = text.indexOf(match); i >= 0; i = text.indexOf(match, i + 1)) {
subs.push([i, i + len, replaceWith]);
}
}
subs.sort((a, b) => a[0] - b[0]);
let i = 0;
function sub(r: SubRange): string {
const [a, b, t] = r;
const prefix = text.slice(i, a);
i = b;
return prefix + t;
}
const parts = subs.map(sub);
return parts.join('') + text.slice(i);
}
export const __testing__ = {
formatIssue,
};