-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
prettierRule.ts
99 lines (88 loc) · 2.72 KB
/
prettierRule.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
import assert = require('assert');
import * as utils from 'eslint-plugin-prettier';
import * as prettier from 'prettier';
import * as tslint from 'tslint';
import * as ts from 'typescript';
// tslint:disable:max-classes-per-file no-use-before-declare
export class Rule extends tslint.Rules.AbstractRule {
public apply(source_file: ts.SourceFile): tslint.RuleFailure[] {
return this.applyWithWalker(
new Walker(source_file, this.ruleName, this.ruleArguments),
);
}
}
class Walker extends tslint.AbstractWalker<any[]> {
public walk(source_file: ts.SourceFile) {
const [rule_argument_1] = this.options;
let options: prettier.Options = {};
switch (typeof rule_argument_1) {
case 'object':
options = rule_argument_1 as prettier.Options;
break;
default:
try {
// tslint:disable-next-line:strict-type-predicates
assert(typeof prettier.resolveConfig.sync === 'function');
} catch {
// backward compatibility: use default options if no resolveConfig.sync()
// istanbul ignore next
break;
}
const resolved_config = prettier.resolveConfig.sync(
source_file.fileName,
);
if (resolved_config !== null) {
options = resolved_config;
}
break;
}
const source = source_file.getFullText();
const formatted = prettier.format(source, {
parser: 'typescript',
...options,
});
if (source === formatted) {
return;
}
utils.generateDifferences(source, formatted).forEach(difference => {
const {
operation,
offset: start,
deleteText: delete_text = '',
insertText: insert_text = '',
} = difference;
const end = start + delete_text.length;
const delete_code = utils.showInvisibles(delete_text);
const insert_code = utils.showInvisibles(insert_text);
switch (operation) {
case 'insert':
this.addFailureAt(
start,
1,
`Insert \`${insert_code}\``,
tslint.Replacement.appendText(start, insert_text),
);
break;
case 'delete':
this.addFailure(
start,
end,
`Delete \`${delete_code}\``,
tslint.Replacement.deleteFromTo(start, end),
);
break;
case 'replace':
this.addFailure(
start,
end,
`Replace \`${delete_code}\` with \`${insert_code}\``,
tslint.Replacement.replaceFromTo(start, end, insert_text),
);
break;
// istanbul ignore next
default:
throw new Error(`Unexpected operation '${operation}'`);
}
});
}
}