forked from palantir/tslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinter.ts
220 lines (192 loc) · 8.4 KB
/
linter.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
/**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as fs from "fs";
import * as ts from "typescript";
import {
DEFAULT_CONFIG,
IConfigurationFile,
findConfiguration,
findConfigurationPath,
getRelativePath,
getRulesDirectories,
loadConfigurationFromPath,
} from "./configuration";
import { EnableDisableRulesWalker } from "./enableDisableRules";
import { findFormatter } from "./formatterLoader";
import { ILinterOptions, LintResult } from "./index";
import { IFormatter } from "./language/formatter/formatter";
import { Fix, IRule, RuleFailure } from "./language/rule/rule";
import { TypedRule } from "./language/rule/typedRule";
import * as utils from "./language/utils";
import { loadRules } from "./ruleLoader";
import { arrayify, dedent } from "./utils";
/**
* Linter that can lint multiple files in consecutive runs.
*/
class Linter {
public static VERSION = "4.0.0-dev";
public static findConfiguration = findConfiguration;
public static findConfigurationPath = findConfigurationPath;
public static getRulesDirectories = getRulesDirectories;
public static loadConfigurationFromPath = loadConfigurationFromPath;
private failures: RuleFailure[] = [];
private fixes: RuleFailure[] = [];
/**
* Creates a TypeScript program object from a tsconfig.json file path and optional project directory.
*/
public static createProgram(configFile: string, projectDirectory?: string): ts.Program {
if (projectDirectory === undefined) {
const lastSeparator = configFile.lastIndexOf("/");
if (lastSeparator < 0) {
projectDirectory = ".";
} else {
projectDirectory = configFile.substring(0, lastSeparator + 1);
}
}
const { config } = ts.readConfigFile(configFile, ts.sys.readFile);
const parseConfigHost = {
fileExists: fs.existsSync,
readDirectory: ts.sys.readDirectory,
useCaseSensitiveFileNames: true,
};
const parsed = ts.parseJsonConfigFileContent(config, parseConfigHost, projectDirectory);
const host = ts.createCompilerHost(parsed.options, true);
const program = ts.createProgram(parsed.fileNames, parsed.options, host);
return program;
}
/**
* Returns a list of source file names from a TypeScript program. This includes all referenced
* files and excludes declaration (".d.ts") files.
*/
public static getFileNames(program: ts.Program): string[] {
return program.getSourceFiles().map(s => s.fileName).filter(l => l.substr(-5) !== ".d.ts");
}
constructor(private options: ILinterOptions, private program?: ts.Program) {
if (typeof options !== "object") {
throw new Error("Unknown Linter options type: " + typeof options);
}
if ((<any> options).configuration != null) {
throw new Error("ILinterOptions does not contain the property `configuration` as of version 4. " +
"Did you mean to pass the `IConfigurationFile` object to lint() ? ");
}
}
public lint(fileName: string, source?: string, configuration: IConfigurationFile = DEFAULT_CONFIG): void {
const enabledRules = this.getEnabledRules(fileName, source, configuration);
let sourceFile = this.getSourceFile(fileName, source);
let hasLinterRun = false;
if (this.options.fix) {
this.fixes = [];
for (let rule of enabledRules) {
let fileFailures = this.applyRule(rule, sourceFile);
const fixes = fileFailures.map(f => f.getFix()).filter(f => !!f);
source = fs.readFileSync(fileName, { encoding: "utf-8" });
if (fixes.length > 0) {
this.fixes = this.fixes.concat(fileFailures);
source = Fix.applyAll(source, fixes);
fs.writeFileSync(fileName, source, { encoding: "utf-8" });
// reload AST if file is modified
sourceFile = this.getSourceFile(fileName, source);
}
this.failures = this.failures.concat(fileFailures);
}
hasLinterRun = true;
}
// make a 1st pass or make a 2nd pass if there were any fixes because the positions may be off
if (!hasLinterRun || this.fixes.length > 0) {
this.failures = [];
for (let rule of enabledRules) {
const fileFailures = this.applyRule(rule, sourceFile);
this.failures = this.failures.concat(fileFailures);
}
}
}
public getResult(): LintResult {
let formatter: IFormatter;
const formattersDirectory = getRelativePath(this.options.formattersDirectory);
const formatterName = this.options.formatter || "prose";
const Formatter = findFormatter(formatterName, formattersDirectory);
if (Formatter) {
formatter = new Formatter();
} else {
throw new Error(`formatter '${formatterName}' not found`);
}
const output = formatter.format(this.failures, this.fixes);
return {
failureCount: this.failures.length,
failures: this.failures,
fixes: this.fixes,
format: formatterName,
output,
};
}
private applyRule(rule: IRule, sourceFile: ts.SourceFile) {
let ruleFailures: RuleFailure[] = [];
if (this.program && rule instanceof TypedRule) {
ruleFailures = rule.applyWithProgram(sourceFile, this.program);
} else {
ruleFailures = rule.apply(sourceFile);
}
let fileFailures: RuleFailure[] = [];
for (let ruleFailure of ruleFailures) {
if (!this.containsRule(this.failures, ruleFailure)) {
fileFailures.push(ruleFailure);
}
}
return fileFailures;
}
private getEnabledRules(fileName: string, source?: string, configuration: IConfigurationFile = DEFAULT_CONFIG): IRule[] {
const sourceFile = this.getSourceFile(fileName, source);
// walk the code first to find all the intervals where rules are disabled
const rulesWalker = new EnableDisableRulesWalker(sourceFile, {
disabledIntervals: [],
ruleName: "",
});
rulesWalker.walk(sourceFile);
const enableDisableRuleMap = rulesWalker.enableDisableRuleMap;
const rulesDirectories = arrayify(this.options.rulesDirectory)
.concat(arrayify(configuration.rulesDirectory));
const isJs = /\.jsx?$/i.test(fileName);
const configurationRules = isJs ? configuration.jsRules : configuration.rules;
let configuredRules = loadRules(configurationRules, enableDisableRuleMap, rulesDirectories, isJs);
return configuredRules.filter((r) => r.isEnabled());
}
private getSourceFile(fileName: string, source?: string) {
let sourceFile: ts.SourceFile;
if (this.program) {
sourceFile = this.program.getSourceFile(fileName);
// check if the program has been type checked
if (sourceFile && !("resolvedModules" in sourceFile)) {
throw new Error("Program must be type checked before linting");
}
} else {
sourceFile = utils.getSourceFile(fileName, source);
}
if (sourceFile === undefined) {
const INVALID_SOURCE_ERROR = dedent`
Invalid source file: ${fileName}. Ensure that the files supplied to lint have a .ts, .tsx, .js or .jsx extension.
`;
throw new Error(INVALID_SOURCE_ERROR);
}
return sourceFile;
}
private containsRule(rules: RuleFailure[], rule: RuleFailure) {
return rules.some((r) => r.equals(rule));
}
}
// tslint:disable-next-line:no-namespace
namespace Linter { }
export = Linter;