-
Notifications
You must be signed in to change notification settings - Fork 198
/
warning.ts
384 lines (344 loc) · 11.5 KB
/
warning.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
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import * as chalk from 'chalk';
import {Analyzer} from '../core/analyzer';
import {UrlResolver} from '../index';
import {ParsedDocument} from '../parser/document';
import {underlineCode} from '../warning/code-printer';
import {Analysis} from './analysis';
import {comparePositionAndRange, isPositionInsideRange, SourceRange} from './source-range';
import {ResolvedUrl} from './url';
const stable = require('stable');
export interface WarningInit {
readonly message: string;
readonly sourceRange: SourceRange;
readonly severity: Severity;
readonly code: string;
readonly parsedDocument: ParsedDocument;
readonly fix?: Edit;
readonly actions?: ReadonlyArray<Action>;
}
export class Warning {
readonly code: string;
readonly message: string;
readonly sourceRange: SourceRange;
readonly severity: Severity;
/**
* If the problem has a single automatic fix, this is it.
*
* Whether and how much something is 'automatic' can be a bit tricky to
* delineate. Roughly speaking, if 99% of the time the change solves the
* issue completely then it should go in `fix`.
*/
readonly fix: Edit|undefined;
/**
* Other actions that could be taken in response to this warning.
*
* Each action is separate and they may be mutually exclusive. In the case
* of edit actions they often are.
*/
readonly actions: ReadonlyArray<Action>|undefined = undefined;
private readonly _parsedDocument: ParsedDocument;
constructor(init: WarningInit) {
({
message: this.message,
sourceRange: this.sourceRange,
severity: this.severity,
code: this.code,
parsedDocument: this._parsedDocument
} = init);
this.fix = init.fix;
this.actions = init.actions;
if (!this.sourceRange) {
throw new Error(
`Attempted to construct a ${this.code} ` +
`warning without a source range.`);
}
if (!this._parsedDocument) {
throw new Error(
`Attempted to construct a ${this.code} ` +
`warning without a parsed document.`);
}
}
toString(options: Partial<WarningStringifyOptions> = {}): string {
const opts:
WarningStringifyOptions = {...defaultPrinterOptions, ...options};
const colorize = opts.color ? this._severityToColorFunction(this.severity) :
(s: string) => s;
const severity = this._severityToString(colorize);
let result = '';
if (options.verbosity !== 'one-line') {
const underlined =
underlineCode(this.sourceRange, this._parsedDocument, colorize);
if (underlined) {
result += underlined;
}
if (options.verbosity === 'code-only') {
return result;
}
result += '\n\n';
}
let file: string = this.sourceRange.file;
if (opts.resolver) {
file = opts.resolver.relative(this.sourceRange.file);
}
result += `${file}(${this.sourceRange.start.line + 1},${
this.sourceRange.start.column +
1}) ${severity} [${this.code}] - ${this.message}\n`;
return result;
}
private _severityToColorFunction(severity: Severity) {
switch (severity) {
case Severity.ERROR:
return chalk.red;
case Severity.WARNING:
return chalk.yellow;
case Severity.INFO:
return chalk.green;
default:
const never: never = severity;
throw new Error(
`Unknown severity value - ${never}` +
` - encountered while printing warning.`);
}
}
private _severityToString(colorize: (s: string) => string) {
switch (this.severity) {
case Severity.ERROR:
return colorize('error');
case Severity.WARNING:
return colorize('warning');
case Severity.INFO:
return colorize('info');
default:
const never: never = this.severity;
throw new Error(
`Unknown severity value - ${never} - ` +
`encountered while printing warning.`);
}
}
toJSON() {
return {
code: this.code,
message: this.message,
severity: this.severity,
sourceRange: this.sourceRange,
};
}
}
export enum Severity {
ERROR,
WARNING,
INFO
}
// TODO(rictic): can we get rid of this class entirely?
export class WarningCarryingException extends Error {
readonly warning: Warning;
constructor(warning: Warning) {
super(warning.message);
this.warning = warning;
}
}
export type Verbosity = 'one-line'|'full'|'code-only';
export interface WarningStringifyOptions {
readonly verbosity: Verbosity;
readonly color: boolean;
/**
* If given, we will use resolver.relative to get a relative path
* to the reported file.
*/
readonly resolver?: UrlResolver;
}
const defaultPrinterOptions = {
verbosity: 'full' as 'full',
color: true
};
export type Action = EditAction|{
/** To ensure that type safe code actually checks for the action kind. */
kind: 'never';
};
/**
* An EditAction is like a fix, only it's not applied automatically when the
* user runs `polymer lint --fix`. Often this is because it's less safe to
* apply automatically, and there may be caveats, or multiple ways to resolve
* the warning.
*
* For example, a change to an element that updates it to no longer use a
* deprecated feature, but that involves a change in the element's API should
* not be a fix, but should instead be an EditAction.
*/
export interface EditAction {
kind: 'edit';
/**
* A unique string code for the edit action. Useful so that the user can
* request that all actions with a given code should be applied.
*/
code: string;
/**
* A short description of the change, noting caveats and important information
* for the user.
*/
description: string;
edit: Edit;
}
/**
* Represents an action for replacing a range in a document with some text.
*
* This is sufficient to represent all operations on text files, including
* inserting and deleting text (using empty ranges or empty replacement
* text, respectively).
*/
export interface Replacement {
readonly range: SourceRange;
readonly replacementText: string;
}
/**
* A set of replacements that must all be applied as a single atomic unit.
*/
export type Edit = ReadonlyArray<Replacement>;
export interface EditResult {
/** The edits that had no conflicts, and are reflected in editedFiles. */
appliedEdits: Edit[];
/** Edits that could not be applied due to overlapping ranges. */
incompatibleEdits: Edit[];
/** A map from urls to their new contents. */
editedFiles: Map<ResolvedUrl, string>;
}
/**
* Takes the given edits and, provided there are no overlaps, applies them to
* the contents loadable from the given loader.
*
* If there are overlapping edits, then edits earlier in the array get priority
* over later ones.
*/
export async function applyEdits(
edits: Edit[], loader: (url: ResolvedUrl) => Promise<ParsedDocument>):
Promise<EditResult> {
const result: EditResult = {
appliedEdits: [],
incompatibleEdits: [],
editedFiles: new Map()
};
const replacementsByFile = new Map<ResolvedUrl, Replacement[]>();
for (const edit of edits) {
if (canApply(edit, replacementsByFile)) {
result.appliedEdits.push(edit);
} else {
result.incompatibleEdits.push(edit);
}
}
for (const [file, replacements] of replacementsByFile) {
const document = await loader(file);
let contents = document.contents;
/**
* This is the important bit. We know that none of the replacements overlap,
* so in order for their source ranges in the file to all be valid at the
* time we apply them, we simply need to apply them starting from the end
* of the document and working backwards to the beginning.
*
* To preserve ordering of insertions to the same position, we use a stable
* sort.
*/
stable.inplace(replacements, (a: Replacement, b: Replacement) => {
const leftEdgeComp =
comparePositionAndRange(b.range.start, a.range, true);
if (leftEdgeComp !== 0) {
return leftEdgeComp;
}
return comparePositionAndRange(b.range.end, a.range, false);
});
for (const replacement of replacements) {
const offsets = document.sourceRangeToOffsets(replacement.range);
contents = contents.slice(0, offsets[0]) + replacement.replacementText +
contents.slice(offsets[1]);
}
result.editedFiles.set(file, contents);
}
return result;
}
/**
* We can apply an edit if none of its replacements overlap with any accepted
* replacement.
*/
function canApply(
edit: Edit, replacements: Map<ResolvedUrl, Replacement[]>): boolean {
for (let i = 0; i < edit.length; i++) {
const replacement = edit[i];
const fileLocalReplacements =
replacements.get(replacement.range.file) || [];
// TODO(rictic): binary search
for (const acceptedReplacement of fileLocalReplacements) {
if (!areReplacementsCompatible(replacement, acceptedReplacement)) {
return false;
}
}
// Also check consistency between multiple replacements in this edit.
for (let j = 0; j < i; j++) {
const acceptedReplacement = edit[j];
if (!areReplacementsCompatible(replacement, acceptedReplacement)) {
return false;
}
}
}
// Ok, we can be applied to the replacements, so add our replacements in.
for (const replacement of edit) {
if (!replacements.has(replacement.range.file)) {
replacements.set(replacement.range.file, [replacement]);
} else {
const fileReplacements = replacements.get(replacement.range.file)!;
fileReplacements.push(replacement);
}
}
return true;
}
function areReplacementsCompatible(a: Replacement, b: Replacement) {
if (a.range.file !== b.range.file) {
return true;
}
if (areRangesEqual(a.range, b.range)) {
// Equal ranges are compatible if the ranges are empty (i.e. the edit is an
// insertion, not a replacement).
return (
a.range.start.column === a.range.end.column &&
a.range.start.line === a.range.end.line);
}
return !(
isPositionInsideRange(a.range.start, b.range, false) ||
isPositionInsideRange(a.range.end, b.range, false) ||
isPositionInsideRange(b.range.start, a.range, false) ||
isPositionInsideRange(b.range.end, a.range, false));
}
function areRangesEqual(a: SourceRange, b: SourceRange) {
return a.start.line === b.start.line && a.start.column === b.start.column &&
a.end.line === b.end.line && a.end.column === b.end.column;
}
export function makeParseLoader(analyzer: Analyzer, analysis?: Analysis) {
return async (url: ResolvedUrl) => {
if (analysis) {
const cachedResult = analysis.getDocument(url);
if (cachedResult.successful) {
return cachedResult.value.parsedDocument;
}
}
const result = (await analyzer.analyze([url])).getDocument(url);
if (result.successful) {
return result.value.parsedDocument;
}
let message = '';
if (result.error) {
message = result.error.message;
}
throw new Error(`Cannot load file at: ${JSON.stringify(url)}: ${message}`);
};
}