This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
/
server.ts
276 lines (242 loc) · 7.7 KB
/
server.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
'use strict';
import * as minimatch from 'minimatch';
import * as server from 'vscode-languageserver';
import * as fs from 'fs';
// Settings as defined in VS Code
interface Settings {
tslint: {
enable: boolean;
rulesDirectory: string | string[];
configFile: string;
ignoreDefinitionFiles: boolean;
exclude: string | string[];
validateWithDefaultConfig: boolean;
};
}
let settings: Settings = null;
let linter: typeof Lint.Linter = null;
let tslintNotFound =
`Failed to load tslint library. Please install tslint in your workspace
folder using \'npm install tslint\' or \'npm install -g tslint\' and then press Retry.`;
// Options passed to tslint
let options: Lint.ILinterOptions = {
formatter: "json",
configuration: {},
rulesDirectory: undefined,
formattersDirectory: undefined
};
let configFile: string = null;
let configFileWatcher: fs.FSWatcher = null;
let configCache = {
filePath: <string>null,
configuration: <any>null,
isDefaultConfig: false
};
function makeDiagnostic(problem: any): server.Diagnostic {
return {
severity: server.DiagnosticSeverity.Warning,
message: problem.failure,
range: {
start: {
line: problem.startPosition.line,
character: problem.startPosition.character
},
end: {
line: problem.endPosition.line,
character: problem.endPosition.character
},
},
code: problem.ruleName,
source: 'tslint'
};
}
function getConfiguration(filePath: string, configFileName: string): any {
if (configCache.configuration && configCache.filePath === filePath) {
return configCache.configuration;
}
configCache = {
filePath: filePath,
isDefaultConfig: linter.findConfigurationPath(configFileName, filePath) === undefined,
configuration: linter.findConfiguration(configFileName, filePath)
};
return configCache.configuration;
}
function flushConfigCache() {
configCache = {
filePath: null,
configuration: null,
isDefaultConfig: false
};
}
function getErrorMessage(err: any, document: server.ITextDocument): string {
let errorMessage = `unknown error`;
if (typeof err.message === 'string' || err.message instanceof String) {
errorMessage = <string>err.message;
}
let fsPath = server.Files.uriToFilePath(document.uri);
let message = `vscode-tslint: '${errorMessage}' while validating: ${fsPath} stacktrace: ${err.stack}`;
return message;
}
function showConfigurationFailure(conn: server.IConnection, err: any) {
let errorMessage = `unknown error`;
if (typeof err.message === 'string' || err.message instanceof String) {
errorMessage = <string>err.message;
}
let message = `vscode-tslint: Cannot read tslint configuration - '${errorMessage}'`;
conn.window.showInformationMessage(message);
}
function validateAllTextDocuments(connection: server.IConnection, documents: server.ITextDocument[]): void {
let tracker = new server.ErrorMessageTracker();
documents.forEach(document => {
try {
validateTextDocument(connection, document);
} catch (err) {
tracker.add(getErrorMessage(err, document));
}
});
tracker.sendErrors(connection);
}
function validateTextDocument(connection: server.IConnection, document: server.ITextDocument): void {
try {
let uri = document.uri;
let diagnostics = doValidate(connection, document);
connection.sendDiagnostics({ uri, diagnostics });
} catch (err) {
connection.window.showErrorMessage(getErrorMessage(err, document));
}
}
let connection: server.IConnection = server.createConnection(process.stdin, process.stdout);
let documents: server.TextDocuments = new server.TextDocuments();
documents.listen(connection);
connection.onInitialize((params): Thenable<server.InitializeResult | server.ResponseError<server.InitializeError>> => {
let rootFolder = params.rootPath;
return server.Files.resolveModule(rootFolder, 'tslint').
then((value): server.InitializeResult | server.ResponseError<server.InitializeError> => {
linter = value;
let result: server.InitializeResult = { capabilities: { textDocumentSync: documents.syncKind } };
return result;
}, (error) => {
return Promise.reject(
new server.ResponseError<server.InitializeError>(99,
tslintNotFound,
{ retry: true }));
});
});
function doValidate(conn: server.IConnection, document: server.ITextDocument): server.Diagnostic[] {
let uri = document.uri;
let diagnostics: server.Diagnostic[] = [];
let fsPath = server.Files.uriToFilePath(uri);
if (!fsPath) {
// tslint can only lint files on disk
return diagnostics;
}
if (fileIsExcluded(fsPath)) {
return diagnostics;
}
let contents = document.getText();
try {
options.configuration = getConfiguration(fsPath, configFile);
} catch (err) {
showConfigurationFailure(conn, err);
return diagnostics;
}
if (settings && settings.tslint && settings.tslint.validateWithDefaultConfig === false && configCache.isDefaultConfig) {
return diagnostics;
}
let result: Lint.LintResult;
try { // protect against tslint crashes
let tslint = new linter(fsPath, contents, options);
result = tslint.lint();
} catch (err) {
// TO DO show an indication in the workbench
conn.console.error(getErrorMessage(err, document));
return diagnostics;
}
if (result.failureCount > 0) {
let problems: any[] = JSON.parse(result.output);
problems.forEach(each => {
diagnostics.push(makeDiagnostic(each));
});
}
return diagnostics;
}
function fileIsExcluded(path: string): boolean {
function testForExclusionPattern(path: string, pattern: string): boolean {
return minimatch(path, pattern)
}
if (settings && settings.tslint) {
if (settings.tslint.ignoreDefinitionFiles) {
if (minimatch(path, "**/*.d.ts")) {
return true;
}
}
if (settings.tslint.exclude) {
if (Array.isArray(settings.tslint.exclude)) {
for (var pattern of settings.tslint.exclude) {
if (testForExclusionPattern(path, pattern)) {
return true;
}
}
}
else if (testForExclusionPattern(path, <string>settings.tslint.exclude)) {
return true;
}
}
}
}
// A text document has changed. Validate the document.
documents.onDidChangeContent((event) => {
// the contents of a text document has changed
validateTextDocument(connection, event.document);
});
function tslintConfigurationValid(): boolean {
try {
documents.all().forEach((each) => {
let fsPath = server.Files.uriToFilePath(each.uri);
if (fsPath) {
getConfiguration(fsPath, configFile);
}
});
} catch (err) {
return false;
}
return true;
}
// The VS Code tslint settings have changed. Revalidate all documents.
connection.onDidChangeConfiguration((params) => {
flushConfigCache();
settings = params.settings;
if (settings.tslint) {
options.rulesDirectory = settings.tslint.rulesDirectory || null;
let newConfigFile = settings.tslint.configFile || null;
if (configFile !== newConfigFile) {
if (configFileWatcher) {
configFileWatcher.close();
configFileWatcher = null;
}
if (!fs.existsSync(newConfigFile)) {
connection.window.showWarningMessage(`The file ${newConfigFile} refered to by 'tslint.configFile' does not exist`);
configFile = null;
return;
}
configFile = newConfigFile;
if (configFile) {
configFileWatcher = fs.watch(configFile, { persistent: false }, (event, fileName) => {
validateAllTextDocuments(connection, documents.all());
});
}
}
}
validateAllTextDocuments(connection, documents.all());
});
// The watched tslint.json has changed. Revalidate all documents, IF the configuration is valid.
connection.onDidChangeWatchedFiles((params) => {
flushConfigCache();
if (tslintConfigurationValid()) {
validateAllTextDocuments(connection, documents.all());
}
});
connection.listen();