This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 86
/
lint.ts
205 lines (180 loc) · 8.16 KB
/
lint.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
import { TypeScriptVersion } from "@definitelytyped/typescript-versions";
import { typeScriptPath } from "@definitelytyped/utils";
import assert = require("assert");
import { pathExists } from "fs-extra";
import { join as joinPaths, normalize } from "path";
import { Configuration, ILinterOptions, Linter } from "tslint";
import * as TsType from "typescript";
type Configuration = typeof Configuration;
type IConfigurationFile = Configuration.IConfigurationFile;
import { getProgram, Options as ExpectOptions } from "./rules/expectRule";
import { readJson, withoutPrefix } from "./util";
export async function lint(
dirPath: string,
minVersion: TsVersion,
maxVersion: TsVersion,
inTypesVersionDirectory: boolean,
expectOnly: boolean,
tsLocal: string | undefined): Promise<string | undefined> {
const tsconfigPath = joinPaths(dirPath, "tsconfig.json");
const lintProgram = Linter.createProgram(tsconfigPath);
for (const version of [maxVersion, minVersion]) {
const errors = testDependencies(version, dirPath, lintProgram, tsLocal);
if (errors) { return errors; }
}
const lintOptions: ILinterOptions = {
fix: false,
formatter: "stylish",
};
const linter = new Linter(lintOptions, lintProgram);
const configPath = expectOnly ? joinPaths(__dirname, "..", "dtslint-expect-only.json") : getConfigPath(dirPath);
const config = await getLintConfig(configPath, tsconfigPath, minVersion, maxVersion, tsLocal);
for (const file of lintProgram.getSourceFiles()) {
if (lintProgram.isSourceFileDefaultLibrary(file)) { continue; }
const { fileName, text } = file;
const err = testNoTsIgnore(text) || testNoTslintDisables(text);
if (err) {
const { pos, message } = err;
const place = file.getLineAndCharacterOfPosition(pos);
return `At ${fileName}:${JSON.stringify(place)}: ${message}`;
}
// External dependencies should have been handled by `testDependencies`;
// typesVersions should be handled in a separate lint
if (!isExternalDependency(file, dirPath, lintProgram) &&
(inTypesVersionDirectory || !isTypesVersionPath(fileName, dirPath))) {
linter.lint(fileName, text, config);
}
}
const result = linter.getResult();
return result.failures.length ? result.output : undefined;
}
function testDependencies(
version: TsVersion,
dirPath: string,
lintProgram: TsType.Program,
tsLocal: string | undefined,
): string | undefined {
const tsconfigPath = joinPaths(dirPath, "tsconfig.json");
assert(version !== "local" || tsLocal);
const ts: typeof TsType = require(typeScriptPath(version, tsLocal));
const program = getProgram(tsconfigPath, ts, version, lintProgram);
const diagnostics = ts.getPreEmitDiagnostics(program).filter(d => !d.file || isExternalDependency(d.file, dirPath, program));
if (!diagnostics.length) { return undefined; }
const showDiags = ts.formatDiagnostics(diagnostics, {
getCanonicalFileName: f => f,
getCurrentDirectory: () => dirPath,
getNewLine: () => "\n",
});
return `Errors in typescript@${version} for external dependencies:\n${showDiags}`;
}
export function isExternalDependency(file: TsType.SourceFile, dirPath: string, program: TsType.Program): boolean {
return !startsWithDirectory(file.fileName, dirPath) || program.isSourceFileFromExternalLibrary(file);
}
function normalizePath(file: string) {
// replaces '\' with '/' and forces all DOS drive letters to be upper-case
return normalize(file)
.replace(/\\/g, "/")
.replace(/^[a-z](?=:)/, c => c.toUpperCase());
}
function isTypesVersionPath(fileName: string, dirPath: string) {
const normalFileName = normalizePath(fileName);
const normalDirPath = normalizePath(dirPath);
const subdirPath = withoutPrefix(normalFileName, normalDirPath);
return subdirPath && /^\/ts\d+\.\d/.test(subdirPath);
}
function startsWithDirectory(filePath: string, dirPath: string): boolean {
const normalFilePath = normalizePath(filePath);
const normalDirPath = normalizePath(dirPath).replace(/\/$/, "");
return normalFilePath.startsWith(normalDirPath + "/") || normalFilePath.startsWith(normalDirPath + "\\");
}
interface Err { pos: number; message: string; }
function testNoTsIgnore(text: string): Err | undefined {
const tsIgnore = "ts-ignore";
const pos = text.indexOf(tsIgnore);
return pos === -1 ? undefined : { pos, message: "'ts-ignore' is forbidden." };
}
function testNoTslintDisables(text: string): Err | undefined {
const tslintDisable = "tslint:disable";
let lastIndex = 0;
while (true) {
const pos = text.indexOf(tslintDisable, lastIndex);
if (pos === -1) {
return undefined;
}
const end = pos + tslintDisable.length;
const nextChar = text.charAt(end);
if (nextChar !== "-" && nextChar !== ":") {
const message = "'tslint:disable' is forbidden. " +
"('tslint:disable:rulename', tslint:disable-line' and 'tslint:disable-next-line' are allowed.)";
return { pos, message };
}
lastIndex = end;
}
}
export async function checkTslintJson(dirPath: string, dt: boolean): Promise<void> {
const configPath = getConfigPath(dirPath);
const shouldExtend = `dtslint/${dt ? "dt" : "dtslint"}.json`;
const validateExtends = (extend: string | string[]) =>
extend === shouldExtend || (!dt && Array.isArray(extend) && extend.some(val => val === shouldExtend));
if (!await pathExists(configPath)) {
if (dt) {
throw new Error(
`On DefinitelyTyped, must include \`tslint.json\` containing \`{ "extends": "${shouldExtend}" }\`.\n` +
"This was inferred as a DefinitelyTyped package because it contains a `// Type definitions for` header.");
}
return;
}
const tslintJson = await readJson(configPath);
if (!validateExtends(tslintJson.extends)) {
throw new Error(`If 'tslint.json' is present, it should extend "${shouldExtend}"`);
}
}
function getConfigPath(dirPath: string): string {
return joinPaths(dirPath, "tslint.json");
}
async function getLintConfig(
expectedConfigPath: string,
tsconfigPath: string,
minVersion: TsVersion,
maxVersion: TsVersion,
tsLocal: string | undefined,
): Promise<IConfigurationFile> {
const configExists = await pathExists(expectedConfigPath);
const configPath = configExists ? expectedConfigPath : joinPaths(__dirname, "..", "dtslint.json");
// Second param to `findConfiguration` doesn't matter, since config path is provided.
const config = Configuration.findConfiguration(configPath, "").results;
if (!config) {
throw new Error(`Could not load config at ${configPath}`);
}
const expectRule = config.rules.get("expect");
if (!expectRule || expectRule.ruleSeverity !== "error") {
throw new Error("'expect' rule should be enabled, else compile errors are ignored");
}
if (expectRule) {
const versionsToTest =
range(minVersion, maxVersion).map(versionName => ({ versionName, path: typeScriptPath(versionName, tsLocal) }));
const expectOptions: ExpectOptions = { tsconfigPath, versionsToTest };
expectRule.ruleArguments = [expectOptions];
}
return config;
}
function range(minVersion: TsVersion, maxVersion: TsVersion): ReadonlyArray<TsVersion> {
if (minVersion === "local") {
assert(maxVersion === "local");
return ["local"];
}
if (minVersion === TypeScriptVersion.latest) {
assert(maxVersion === TypeScriptVersion.latest);
return [TypeScriptVersion.latest];
}
assert(maxVersion !== "local");
const minIdx = TypeScriptVersion.shipped.indexOf(minVersion);
assert(minIdx >= 0);
if (maxVersion === TypeScriptVersion.latest) {
return [...TypeScriptVersion.shipped.slice(minIdx), TypeScriptVersion.latest];
}
const maxIdx = TypeScriptVersion.shipped.indexOf(maxVersion as TypeScriptVersion);
assert(maxIdx >= minIdx);
return TypeScriptVersion.shipped.slice(minIdx, maxIdx + 1);
}
export type TsVersion = TypeScriptVersion | "local";