-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
server.ts
471 lines (430 loc) · 16.9 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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/* --------------------------------------------------------------------------------------------
* Copyright (c) Remy Suen. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import {
createConnection, IConnection, InitializeResult, ClientCapabilities,
TextDocumentPositionParams, TextDocumentSyncKind, TextDocument, TextEdit, Hover,
CompletionItem, CodeActionParams, Command, ExecuteCommandParams,
DocumentSymbolParams, SymbolInformation, SignatureHelp,
DocumentFormattingParams, DocumentRangeFormattingParams, DocumentOnTypeFormattingParams, DocumentHighlight,
RenameParams, WorkspaceEdit, Location,
DidChangeTextDocumentParams, DidOpenTextDocumentParams, DidCloseTextDocumentParams, TextDocumentContentChangeEvent,
DidChangeConfigurationNotification, ProposedFeatures
} from 'vscode-languageserver';
import { Validator, ValidationSeverity } from './dockerValidator';
import { ValidatorSettings } from './dockerValidatorSettings';
import { DockerAssist } from './dockerAssist';
import { CommandIds, DockerCommands } from './dockerCommands';
import { DockerHover } from './dockerHover';
import { MarkdownDocumentation } from './dockerMarkdown';
import { PlainTextDocumentation } from './dockerPlainText';
import { DockerSignatures } from './dockerSignatures';
import { DockerSymbols } from './dockerSymbols';
import { DockerFormatter } from './dockerFormatter';
import { DockerHighlight } from './dockerHighlight';
import { DockerRename } from './dockerRename';
import { DockerDefinition } from './dockerDefinition';
import { DockerRegistryClient } from './dockerRegistryClient';
let markdown = new MarkdownDocumentation();
let hoverProvider = new DockerHover(markdown);
let commandsProvider = new DockerCommands();
let symbolsProvider = new DockerSymbols();
let formatterProvider = new DockerFormatter();
let definitionProvider = new DockerDefinition();
let documentationResolver = new PlainTextDocumentation();
let signatureHelp = new DockerSignatures();
/**
* The settings to use for the validator if the client doesn't support
* workspace/configuration requests.
*/
let validatorSettings = null;
/**
* The validator settings that correspond to an individual file retrieved via
* the workspace/configuration request.
*/
let validatorConfigurations: Map<string, Thenable<ValidatorConfiguration>> = new Map();
let connection = createConnection(ProposedFeatures.all);
let dockerRegistryClient = new DockerRegistryClient(connection);
let snippetSupport: boolean = false;
/**
* Whether the client supports the workspace/configuration request.
*/
let configurationSupport: boolean = false;
let documents: any = {};
function supportsSnippets(capabilities: ClientCapabilities): boolean {
return capabilities.textDocument
&& capabilities.textDocument.completion
&& capabilities.textDocument.completion.completionItem
&& capabilities.textDocument.completion.completionItem.snippetSupport;
}
connection.onInitialized(() => {
if (configurationSupport) {
// listen for notification changes if the client supports workspace/configuration
connection.client.register(DidChangeConfigurationNotification.type);
}
});
connection.onInitialize((params): InitializeResult => {
snippetSupport = supportsSnippets(params.capabilities);
configurationSupport = params.capabilities.workspace && (params.capabilities.workspace as any).configuration === true;
return {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Incremental,
codeActionProvider: true,
completionProvider: {
resolveProvider: true,
triggerCharacters: [
'=',
' ',
'$',
'-',
]
},
executeCommandProvider: {
commands: [
CommandIds.LOWERCASE,
CommandIds.UPPERCASE,
CommandIds.EXTRA_ARGUMENT,
CommandIds.DIRECTIVE_TO_BACKSLASH,
CommandIds.DIRECTIVE_TO_BACKTICK,
CommandIds.FLAG_TO_COPY_FROM,
CommandIds.FLAG_TO_HEALTHCHECK_INTERVAL,
CommandIds.FLAG_TO_HEALTHCHECK_RETRIES,
CommandIds.FLAG_TO_HEALTHCHECK_START_PERIOD,
CommandIds.FLAG_TO_HEALTHCHECK_TIMEOUT,
CommandIds.CONVERT_TO_AS
]
},
documentFormattingProvider: true,
documentRangeFormattingProvider: true,
documentOnTypeFormattingProvider: {
firstTriggerCharacter: '\\',
moreTriggerCharacter: [ '`' ]
},
hoverProvider: true,
documentSymbolProvider: true,
documentHighlightProvider: true,
renameProvider: true,
definitionProvider: true,
signatureHelpProvider: {
triggerCharacters: [
'-',
'[',
',',
' ',
'='
]
}
}
}
});
function validateTextDocument(textDocument: TextDocument): void {
if (configurationSupport) {
getConfiguration(textDocument.uri).then((config: ValidatorConfiguration) => {
let maintainer = ValidationSeverity.WARNING;
let directiveCasing = ValidationSeverity.WARNING;
let instructionCasing = ValidationSeverity.WARNING;
let instructionCmdMultiple = ValidationSeverity.WARNING;
let instructionEntrypointMultiple = ValidationSeverity.WARNING;
let instructionHealthcheckMultiple = ValidationSeverity.WARNING;
if (config) {
maintainer = getSeverity(config.deprecatedMaintainer);
directiveCasing = getSeverity(config.directiveCasing);
instructionCasing = getSeverity(config.instructionCasing);
instructionCmdMultiple = getSeverity(config.instructionCmdMultiple);
instructionEntrypointMultiple = getSeverity(config.instructionEntrypointMultiple);
instructionHealthcheckMultiple = getSeverity(config.instructionHealthcheckMultiple);
}
const fileSettings = {
deprecatedMaintainer: maintainer,
directiveCasing: directiveCasing,
instructionCasing: instructionCasing,
instructionCmdMultiple: instructionCmdMultiple,
instructionEntrypointMultiple: instructionEntrypointMultiple,
instructionHealthcheckMultiple: instructionHealthcheckMultiple
};
const validator = new Validator(fileSettings);
const diagnostics = validator.validate(textDocument);
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
});
} else {
const validator = new Validator(validatorSettings);
const diagnostics = validator.validate(textDocument);
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}
}
interface ValidatorConfiguration {
deprecatedMaintainer?: string,
directiveCasing?: string,
instructionCasing?: string,
instructionCmdMultiple?: string,
instructionEntrypointMultiple?: string,
instructionHealthcheckMultiple?: string
}
interface Settings {
docker: {
languageserver: {
diagnostics?: ValidatorConfiguration
}
}
}
function getSeverity(severity: string): ValidationSeverity {
switch (severity) {
case "ignore":
return ValidationSeverity.IGNORE;
case "warning":
return ValidationSeverity.WARNING;
case "error":
return ValidationSeverity.ERROR;
}
return null;
}
/**
* Gets the validation configuration that pertains to the specified resource.
*
* @param resource the interested resource
* @return the configuration to use to validate the interested resource
*/
function getConfiguration(resource: string): Thenable<ValidatorConfiguration> {
let result = validatorConfigurations.get(resource);
if (!result) {
result = connection.workspace.getConfiguration({ section: '', scopeUri: resource });
validatorConfigurations.set(resource, result);
}
return result;
}
// listen for notifications when the client's configuration has changed
connection.onNotification(DidChangeConfigurationNotification.type, () => {
refreshConfigurations();
});
/**
* Wipes and reloads the internal cache of validator configurations.
*/
function refreshConfigurations() {
// store all the URIs that need to be refreshed
const settingsRequest = [];
for (let uri in documents) {
settingsRequest.push({ section: "", scopeUri: uri });
}
// clear the cache
validatorConfigurations.clear();
// ask the workspace for the configurations
connection.workspace.getConfiguration(settingsRequest).then((values: ValidatorConfiguration[]) => {
const toRevalidate: string[] = [];
for (let i = 0; i < values.length; i++) {
const resource = settingsRequest[i].scopeUri;
// a value might have been stored already, use it instead and ignore this one if so
if (values[i] && !validatorConfigurations.has(resource)) {
validatorConfigurations.set(resource, Promise.resolve(values[i]));
toRevalidate.push(resource);
}
}
for (const resource of toRevalidate) {
validateTextDocument(documents[resource]);
}
});
}
connection.onDidChangeConfiguration((change) => {
if (configurationSupport) {
refreshConfigurations();
} else {
let settings = <Settings>change.settings;
let maintainer = ValidationSeverity.WARNING;
let directiveCasing = ValidationSeverity.WARNING;
let instructionCasing = ValidationSeverity.WARNING;
let instructionCmdMultiple = ValidationSeverity.WARNING;
let instructionEntrypointMultiple = ValidationSeverity.WARNING;
let instructionHealthcheckMultiple = ValidationSeverity.WARNING;
if (settings.docker && settings.docker.languageserver && settings.docker.languageserver.diagnostics) {
maintainer = getSeverity(settings.docker.languageserver.diagnostics.deprecatedMaintainer);
directiveCasing = getSeverity(settings.docker.languageserver.diagnostics.directiveCasing);
instructionCasing = getSeverity(settings.docker.languageserver.diagnostics.instructionCasing);
instructionCmdMultiple = getSeverity(settings.docker.languageserver.diagnostics.instructionCmdMultiple);
instructionEntrypointMultiple = getSeverity(settings.docker.languageserver.diagnostics.instructionEntrypointMultiple);
instructionHealthcheckMultiple = getSeverity(settings.docker.languageserver.diagnostics.instructionHealthcheckMultiple);
}
validatorSettings = {
deprecatedMaintainer: maintainer,
directiveCasing: directiveCasing,
instructionCasing: instructionCasing,
instructionCmdMultiple: instructionCmdMultiple,
instructionEntrypointMultiple: instructionEntrypointMultiple,
instructionHealthcheckMultiple: instructionHealthcheckMultiple
};
// validate all the documents again
Object.keys(documents).forEach((key) => {
validateTextDocument(documents[key]);
});
}
});
connection.onCompletion((textDocumentPosition: TextDocumentPositionParams): CompletionItem[] | PromiseLike<CompletionItem[]> => {
let document = documents[textDocumentPosition.textDocument.uri];
if (document) {
let assist = new DockerAssist(document, snippetSupport, dockerRegistryClient);
return assist.computeProposals(document, textDocumentPosition.position);
}
return null;
});
connection.onSignatureHelp((textDocumentPosition: TextDocumentPositionParams): SignatureHelp => {
let document = documents[textDocumentPosition.textDocument.uri];
if (document !== null) {
return signatureHelp.computeSignatures(document, textDocumentPosition.position);
}
return {
signatures: [],
activeSignature: null,
activeParameter: null,
};
});
connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
if (!item.documentation) {
item.documentation = documentationResolver.getDocumentation(item.data);
}
return item;
});
connection.onHover((textDocumentPosition: TextDocumentPositionParams): Hover => {
let document = documents[textDocumentPosition.textDocument.uri];
if (document !== null) {
return hoverProvider.onHover(document, textDocumentPosition);
}
return null;
});
connection.onDocumentHighlight((textDocumentPosition: TextDocumentPositionParams): DocumentHighlight[] => {
let document = documents[textDocumentPosition.textDocument.uri];
if (document) {
let highlightProvider = new DockerHighlight();
return highlightProvider.computeHighlightRanges(document, textDocumentPosition.position);
}
return [];
});
connection.onCodeAction((codeActionParams: CodeActionParams): Command[] => {
if (codeActionParams.context.diagnostics.length > 0) {
return commandsProvider.analyzeDiagnostics(
codeActionParams.context.diagnostics, codeActionParams.textDocument.uri, codeActionParams.range
);
}
return [];
});
connection.onExecuteCommand((params: ExecuteCommandParams): void => {
let uri: string = params.arguments[0];
let document = documents[uri];
if (document) {
let edit = commandsProvider.createWorkspaceEdit(document, params);
if (edit) {
connection.workspace.applyEdit(edit);
}
}
});
connection.onDefinition((textDocumentPosition: TextDocumentPositionParams): Location => {
let uri = textDocumentPosition.textDocument.uri;
let document = documents[uri];
if (document) {
return definitionProvider.computeDefinition(document, textDocumentPosition.position);
}
return null;
});
connection.onRenameRequest((params: RenameParams): WorkspaceEdit => {
let document = documents[params.textDocument.uri];
if (document) {
let rename = new DockerRename();
let edits = rename.rename(document, params.position, params.newName);
return {
changes: {
[ params.textDocument.uri ]: edits
}
};
}
return null;
});
connection.onDocumentSymbol((documentSymbolParams: DocumentSymbolParams): SymbolInformation[] => {
let uri = documentSymbolParams.textDocument.uri;
let document = documents[uri];
if (document) {
return symbolsProvider.parseSymbolInformation(document, uri);
}
return [];
});
connection.onDocumentFormatting((documentFormattingParams: DocumentFormattingParams): TextEdit[] => {
let document = documents[documentFormattingParams.textDocument.uri];
if (document) {
return formatterProvider.formatDocument(document, documentFormattingParams.options);
}
return [];
});
connection.onDocumentRangeFormatting((rangeFormattingParams: DocumentRangeFormattingParams): TextEdit[] => {
let document = documents[rangeFormattingParams.textDocument.uri];
if (document) {
return formatterProvider.formatRange(document, rangeFormattingParams.range, rangeFormattingParams.options);
}
return [];
});
connection.onDocumentOnTypeFormatting((onTypeFormattingParams: DocumentOnTypeFormattingParams): TextEdit[] => {
const document = documents[onTypeFormattingParams.textDocument.uri];
if (document) {
return formatterProvider.formatOnType(document, onTypeFormattingParams.position, onTypeFormattingParams.ch, onTypeFormattingParams.options);
}
return [];
});
connection.onDidOpenTextDocument((didOpenTextDocumentParams: DidOpenTextDocumentParams): void => {
let document = TextDocument.create(didOpenTextDocumentParams.textDocument.uri, didOpenTextDocumentParams.textDocument.languageId, didOpenTextDocumentParams.textDocument.version, didOpenTextDocumentParams.textDocument.text);
documents[didOpenTextDocumentParams.textDocument.uri] = document;
validateTextDocument(document);
});
function getLaterChange(changes: TextDocumentContentChangeEvent[], i: number, j: number): number {
if (changes[i].range.start.line === changes[j].range.start.line) {
return changes[i].range.start.character < changes[j].range.start.character ? j : i;
} else if (changes[i].range.start.line < changes[j].range.start.line) {
return j;
}
return i;
}
function sortChanges(changes: TextDocumentContentChangeEvent[]): TextDocumentContentChangeEvent[] {
let sorted = [];
let length = changes.length;
for (let i = 0; i < length; i++) {
let candidate = 0;
for (let j = 1; j < changes.length; j++) {
candidate = getLaterChange(changes, candidate, j);
}
sorted.push(changes[candidate]);
changes.splice(candidate, 1);
}
return sorted;
}
function handleChanges(document: TextDocument, content: string, changes: TextDocumentContentChangeEvent[]) {
if (changes.length === 1 && !changes[0].range) {
// not an incremental change
return changes[0].text;
} else if (changes.length !== 0) {
changes = sortChanges(changes);
for (let i = 0; i < changes.length; i++) {
let offset = document.offsetAt(changes[i].range.start);
let end = null;
if (changes[i].range.end) {
end = document.offsetAt(changes[i].range.end);
} else {
end = offset + changes[i].rangeLength;
}
content = content.substring(0, offset) + changes[i].text + content.substring(end);
}
}
return content;
}
connection.onDidChangeTextDocument((didChangeTextDocumentParams: DidChangeTextDocumentParams): void => {
let document: TextDocument = documents[didChangeTextDocumentParams.textDocument.uri];
let buffer = document.getText();
let changes = didChangeTextDocumentParams.contentChanges;
let changed = handleChanges(document, buffer, changes)
if (changed !== buffer) {
document = TextDocument.create(didChangeTextDocumentParams.textDocument.uri, document.languageId, didChangeTextDocumentParams.textDocument.version, changed);
documents[didChangeTextDocumentParams.textDocument.uri] = document;
validateTextDocument(document);
}
});
connection.onDidCloseTextDocument((didCloseTextDocumentParams: DidCloseTextDocumentParams): void => {
validatorConfigurations.delete(didCloseTextDocumentParams.textDocument.uri);
delete documents[didCloseTextDocumentParams.textDocument.uri];
});
// setup complete, start listening for a client connection
connection.listen();