forked from redhat-developer/yaml-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyamlCodeActions.ts
More file actions
381 lines (355 loc) · 14.2 KB
/
yamlCodeActions.ts
File metadata and controls
381 lines (355 loc) · 14.2 KB
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TextDocument } from 'vscode-languageserver-textdocument';
import {
CodeAction,
CodeActionKind,
Command,
Diagnostic,
Position,
Range,
TextEdit,
WorkspaceEdit,
} from 'vscode-languageserver-types';
import { ClientCapabilities, CodeActionParams } from 'vscode-languageserver-protocol';
import { YamlCommands } from '../../commands';
import * as path from 'path';
import { TextBuffer } from '../utils/textBuffer';
import { LanguageSettings } from '../yamlLanguageService';
import { YAML_SOURCE } from '../parser/jsonParser07';
import { getFirstNonWhitespaceCharacterAfterOffset } from '../utils/strings';
import { matchOffsetToDocument } from '../utils/arrUtils';
import { CST, isMap, isSeq, YAMLMap } from 'yaml';
import { yamlDocumentsCache } from '../parser/yaml-documents';
import { FlowStyleRewriter } from '../utils/flow-style-rewriter';
import { ASTNode } from '../jsonASTTypes';
import * as _ from 'lodash';
import { SourceToken } from 'yaml/dist/parse/cst';
import { ErrorCode } from 'vscode-json-languageservice';
import * as l10n from '@vscode/l10n';
interface YamlDiagnosticData {
schemaUri: string[];
values?: string[];
properties?: string[];
}
export class YamlCodeActions {
private indentation = ' ';
constructor(private readonly clientCapabilities: ClientCapabilities) {}
configure(settings: LanguageSettings): void {
this.indentation = settings.indentation;
}
getCodeAction(document: TextDocument, params: CodeActionParams): CodeAction[] | undefined {
if (!params.context.diagnostics) {
return;
}
const result = [];
result.push(...this.getConvertToBooleanActions(params.context.diagnostics, document));
result.push(...this.getJumpToSchemaActions(params.context.diagnostics));
result.push(...this.getTabToSpaceConverting(params.context.diagnostics, document));
result.push(...this.getUnusedAnchorsDelete(params.context.diagnostics, document));
result.push(...this.getConvertToBlockStyleActions(params.context.diagnostics, document));
result.push(...this.getKeyOrderActions(params.context.diagnostics, document));
result.push(...this.getQuickFixForPropertyOrValueMismatch(params.context.diagnostics, document));
return result;
}
private getJumpToSchemaActions(diagnostics: Diagnostic[]): CodeAction[] {
const isOpenTextDocumentEnabled = this.clientCapabilities?.window?.showDocument?.support ?? false;
if (!isOpenTextDocumentEnabled) {
return [];
}
const schemaUriToDiagnostic = new Map<string, Diagnostic[]>();
for (const diagnostic of diagnostics) {
const schemaUri = (diagnostic.data as YamlDiagnosticData)?.schemaUri || [];
for (const schemaUriStr of schemaUri) {
if (schemaUriStr) {
if (!schemaUriToDiagnostic.has(schemaUriStr)) {
schemaUriToDiagnostic.set(schemaUriStr, []);
}
schemaUriToDiagnostic.get(schemaUriStr).push(diagnostic);
}
}
}
const result = [];
for (const schemaUri of schemaUriToDiagnostic.keys()) {
const action = CodeAction.create(
l10n.t('jumpToSchema', path.basename(schemaUri)),
Command.create('JumpToSchema', YamlCommands.JUMP_TO_SCHEMA, schemaUri)
);
action.diagnostics = schemaUriToDiagnostic.get(schemaUri);
result.push(action);
}
return result;
}
private getTabToSpaceConverting(diagnostics: Diagnostic[], document: TextDocument): CodeAction[] {
const result: CodeAction[] = [];
const textBuff = new TextBuffer(document);
const processedLine: number[] = [];
for (const diag of diagnostics) {
if (diag.message === 'Tabs are not allowed as indentation') {
if (processedLine.includes(diag.range.start.line)) {
continue;
}
const lineContent = textBuff.getLineContent(diag.range.start.line);
let replacedTabs = 0;
let newText = '';
for (let i = diag.range.start.character; i <= diag.range.end.character; i++) {
const char = lineContent.charAt(i);
if (char !== '\t') {
break;
}
replacedTabs++;
newText += this.indentation;
}
processedLine.push(diag.range.start.line);
let resultRange = diag.range;
if (replacedTabs !== diag.range.end.character - diag.range.start.character) {
resultRange = Range.create(
diag.range.start,
Position.create(diag.range.end.line, diag.range.start.character + replacedTabs)
);
}
result.push(
CodeAction.create(
l10n.t('convertToSpace'),
createWorkspaceEdit(document.uri, [TextEdit.replace(resultRange, newText)]),
CodeActionKind.QuickFix
)
);
}
}
if (result.length !== 0) {
const replaceEdits: TextEdit[] = [];
for (let i = 0; i <= textBuff.getLineCount(); i++) {
const lineContent = textBuff.getLineContent(i);
let replacedTabs = 0;
let newText = '';
for (let j = 0; j < lineContent.length; j++) {
const char = lineContent.charAt(j);
if (char !== ' ' && char !== '\t') {
if (replacedTabs !== 0) {
replaceEdits.push(TextEdit.replace(Range.create(i, j - replacedTabs, i, j), newText));
replacedTabs = 0;
newText = '';
}
break;
}
if (char === ' ' && replacedTabs !== 0) {
replaceEdits.push(TextEdit.replace(Range.create(i, j - replacedTabs, i, j), newText));
replacedTabs = 0;
newText = '';
continue;
}
if (char === '\t') {
newText += this.indentation;
replacedTabs++;
}
}
// line contains only tabs
if (replacedTabs !== 0) {
replaceEdits.push(TextEdit.replace(Range.create(i, 0, i, textBuff.getLineLength(i)), newText));
}
}
if (replaceEdits.length > 0) {
result.push(
CodeAction.create(
l10n.t('convertAllSpaceToTab'),
createWorkspaceEdit(document.uri, replaceEdits),
CodeActionKind.QuickFix
)
);
}
}
return result;
}
private getUnusedAnchorsDelete(diagnostics: Diagnostic[], document: TextDocument): CodeAction[] {
const result = [];
const buffer = new TextBuffer(document);
for (const diag of diagnostics) {
if (diag.message.startsWith('Unused anchor') && diag.source === YAML_SOURCE) {
const range = Range.create(diag.range.start, diag.range.end);
const actual = buffer.getText(range);
const lineContent = buffer.getLineContent(range.end.line);
const lastWhitespaceChar = getFirstNonWhitespaceCharacterAfterOffset(lineContent, range.end.character);
range.end.character = lastWhitespaceChar;
const action = CodeAction.create(
l10n.t('deleteUnusedAnchor', actual),
createWorkspaceEdit(document.uri, [TextEdit.del(range)]),
CodeActionKind.QuickFix
);
action.diagnostics = [diag];
result.push(action);
}
}
return result;
}
private getConvertToBooleanActions(diagnostics: Diagnostic[], document: TextDocument): CodeAction[] {
const results: CodeAction[] = [];
for (const diagnostic of diagnostics) {
if (diagnostic.message === 'Incorrect type. Expected "boolean".') {
const value = document.getText(diagnostic.range).toLocaleLowerCase();
if (value === '"true"' || value === '"false"' || value === "'true'" || value === "'false'") {
const newValue = value.includes('true') ? 'true' : 'false';
results.push(
CodeAction.create(
l10n.t('convertToBoolean'),
createWorkspaceEdit(document.uri, [TextEdit.replace(diagnostic.range, newValue)]),
CodeActionKind.QuickFix
)
);
}
}
}
return results;
}
private getConvertToBlockStyleActions(diagnostics: Diagnostic[], document: TextDocument): CodeAction[] {
const results: CodeAction[] = [];
for (const diagnostic of diagnostics) {
if (diagnostic.code === 'flowMap' || diagnostic.code === 'flowSeq') {
const node = getNodeForDiagnostic(document, diagnostic);
if (isMap(node.internalNode) || isSeq(node.internalNode)) {
const blockTypeDescription = isMap(node.internalNode) ? 'map' : 'sequence';
const rewriter = new FlowStyleRewriter(this.indentation);
results.push(
CodeAction.create(
l10n.t('convertToBlockStyle', 'Convert to block style {0}', blockTypeDescription),
createWorkspaceEdit(document.uri, [TextEdit.replace(diagnostic.range, rewriter.write(node))]),
CodeActionKind.QuickFix
)
);
}
}
}
return results;
}
private getKeyOrderActions(diagnostics: Diagnostic[], document: TextDocument): CodeAction[] {
const results: CodeAction[] = [];
for (const diagnostic of diagnostics) {
if (diagnostic?.code === 'mapKeyOrder') {
let node = getNodeForDiagnostic(document, diagnostic);
while (node && node.type !== 'object') {
node = node.parent;
}
if (node && isMap(node.internalNode)) {
const sorted: YAMLMap = _.cloneDeep(node.internalNode);
if (
(sorted.srcToken.type === 'block-map' || sorted.srcToken.type === 'flow-collection') &&
(node.internalNode.srcToken.type === 'block-map' || node.internalNode.srcToken.type === 'flow-collection')
) {
sorted.srcToken.items.sort((a, b) => {
if (a.key && b.key && CST.isScalar(a.key) && CST.isScalar(b.key)) {
return a.key.source.localeCompare(b.key.source);
}
if (!a.key && b.key) {
return -1;
}
if (a.key && !b.key) {
return 1;
}
if (!a.key && !b.key) {
return 0;
}
});
for (let i = 0; i < sorted.srcToken.items.length; i++) {
const item = sorted.srcToken.items[i];
const uItem = node.internalNode.srcToken.items[i];
item.start = uItem.start;
if (
item.value?.type === 'alias' ||
item.value?.type === 'scalar' ||
item.value?.type === 'single-quoted-scalar' ||
item.value?.type === 'double-quoted-scalar'
) {
const newLineIndex = item.value?.end?.findIndex((p) => p.type === 'newline') ?? -1;
let newLineToken = null;
if (uItem.value?.type === 'block-scalar') {
newLineToken = uItem.value?.props?.find((p) => p.type === 'newline');
} else if (CST.isScalar(uItem.value)) {
newLineToken = uItem.value?.end?.find((p) => p.type === 'newline');
}
if (newLineToken && newLineIndex < 0) {
item.value.end = item.value.end ?? [];
item.value.end.push(newLineToken as SourceToken);
}
if (!newLineToken && newLineIndex > -1) {
item.value.end.splice(newLineIndex, 1);
}
} else if (item.value?.type === 'block-scalar') {
const newline = item.value.props.find((p) => p.type === 'newline');
if (!newline) {
item.value.props.push({ type: 'newline', indent: 0, offset: item.value.offset, source: '\n' } as SourceToken);
}
}
}
}
const replaceRange = Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
results.push(
CodeAction.create(
l10n.t('fixKeyOrderToMap'),
createWorkspaceEdit(document.uri, [TextEdit.replace(replaceRange, CST.stringify(sorted.srcToken))]),
CodeActionKind.QuickFix
)
);
}
}
}
return results;
}
/**
* Check if diagnostic contains info for quick fix
* Supports Enum/Const/Property mismatch
*/
private getPossibleQuickFixValues(diagnostic: Diagnostic): string[] | undefined {
if (typeof diagnostic.data !== 'object') {
return;
}
if (
diagnostic.code === ErrorCode.EnumValueMismatch &&
'values' in diagnostic.data &&
Array.isArray((diagnostic.data as YamlDiagnosticData).values)
) {
return (diagnostic.data as YamlDiagnosticData).values;
} else if (
diagnostic.code === ErrorCode.PropertyExpected &&
'properties' in diagnostic.data &&
Array.isArray((diagnostic.data as YamlDiagnosticData).properties)
) {
return (diagnostic.data as YamlDiagnosticData).properties;
}
}
private getQuickFixForPropertyOrValueMismatch(diagnostics: Diagnostic[], document: TextDocument): CodeAction[] {
const results: CodeAction[] = [];
for (const diagnostic of diagnostics) {
const values = this.getPossibleQuickFixValues(diagnostic);
if (!values?.length) {
continue;
}
for (const value of values) {
results.push(
CodeAction.create(
String(value),
createWorkspaceEdit(document.uri, [TextEdit.replace(diagnostic.range, String(value))]),
CodeActionKind.QuickFix
)
);
}
}
return results;
}
}
function getNodeForDiagnostic(document: TextDocument, diagnostic: Diagnostic): ASTNode {
const yamlDocuments = yamlDocumentsCache.getYamlDocument(document);
const startOffset = document.offsetAt(diagnostic.range.start);
const yamlDoc = matchOffsetToDocument(startOffset, yamlDocuments);
const node = yamlDoc.getNodeFromOffset(startOffset);
return node;
}
function createWorkspaceEdit(uri: string, edits: TextEdit[]): WorkspaceEdit {
const changes = {};
changes[uri] = edits;
const edit: WorkspaceEdit = {
changes,
};
return edit;
}