forked from redhat-developer/yaml-language-server
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathyaml-documents.ts
More file actions
266 lines (237 loc) · 8.48 KB
/
yaml-documents.ts
File metadata and controls
266 lines (237 loc) · 8.48 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
/*---------------------------------------------------------------------------------------------
* 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 { JSONDocument } from './jsonParser07';
import { Document, isNode, isPair, isScalar, LineCounter, visit, YAMLError } from 'yaml';
import { ASTNode, YamlNode } from '../jsonASTTypes';
import { defaultOptions, parse as parseYAML, ParserOptions } from './yamlParser07';
import { ErrorCode } from 'vscode-json-languageservice';
import { Node } from 'yaml';
import { convertAST } from './ast-converter';
import { YAMLDocDiagnostic } from '../utils/parseUtils';
import { isArrayEqual } from '../utils/arrUtils';
import { getParent } from '../utils/astUtils';
import { TextBuffer } from '../utils/textBuffer';
import { getIndentation } from '../utils/strings';
import { Token } from 'yaml/dist/parse/cst';
/**
* These documents are collected into a final YAMLDocument
* and passed to the `parseYAML` caller.
*/
export class SingleYAMLDocument extends JSONDocument {
private lineCounter: LineCounter;
private _internalDocument: Document;
public root: ASTNode;
public currentDocIndex: number;
private _lineComments: string[];
constructor(lineCounter?: LineCounter) {
super(null, []);
this.lineCounter = lineCounter;
}
private collectLineComments(): void {
this._lineComments = [];
if (this._internalDocument.commentBefore) {
const comments = this._internalDocument.commentBefore.split('\n');
comments.forEach((comment) => this._lineComments.push(`#${comment}`));
}
visit(this.internalDocument, (_key, node: Node) => {
if (node?.commentBefore) {
const comments = node?.commentBefore.split('\n');
comments.forEach((comment) => this._lineComments.push(`#${comment}`));
}
if (node?.comment) {
this._lineComments.push(`#${node.comment}`);
}
});
if (this._internalDocument.comment) {
this._lineComments.push(`#${this._internalDocument.comment}`);
}
}
set internalDocument(document: Document) {
this._internalDocument = document;
this.root = convertAST(null, this._internalDocument.contents as Node, this._internalDocument, this.lineCounter);
}
get internalDocument(): Document {
return this._internalDocument;
}
get lineComments(): string[] {
if (!this._lineComments) {
this.collectLineComments();
}
return this._lineComments;
}
set lineComments(val: string[]) {
this._lineComments = val;
}
get errors(): YAMLDocDiagnostic[] {
return this.internalDocument.errors.map(YAMLErrorToYamlDocDiagnostics);
}
get warnings(): YAMLDocDiagnostic[] {
return this.internalDocument.warnings.map(YAMLErrorToYamlDocDiagnostics);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
public getSchemas(schema: any, doc: any, node: any): any[] {
const matchingSchemas = [];
doc.validate(schema, matchingSchemas, node.start);
return matchingSchemas;
}
getNodeFromPosition(positionOffset: number, textBuffer: TextBuffer): [YamlNode | undefined, boolean] {
const position = textBuffer.getPosition(positionOffset);
const lineContent = textBuffer.getLineContent(position.line);
if (lineContent.trim().length === 0) {
return [this.findClosestNode(positionOffset, textBuffer), true];
}
let closestNode: Node;
visit(this.internalDocument, (key, node: Node) => {
if (!node) {
return;
}
const range = node.range;
if (!range) {
return;
}
if (range[0] <= positionOffset && range[1] >= positionOffset) {
closestNode = node;
} else {
return visit.SKIP;
}
});
return [closestNode, false];
}
findClosestNode(offset: number, textBuffer: TextBuffer): YamlNode {
let offsetDiff = this.internalDocument.range[2];
let maxOffset = this.internalDocument.range[0];
let closestNode: YamlNode;
visit(this.internalDocument, (key, node: Node) => {
if (!node) {
return;
}
const range = node.range;
if (!range) {
return;
}
const diff = range[2] - offset;
if (maxOffset <= range[0] && diff <= 0 && Math.abs(diff) <= offsetDiff) {
offsetDiff = Math.abs(diff);
maxOffset = range[0];
closestNode = node;
}
});
const position = textBuffer.getPosition(offset);
const lineContent = textBuffer.getLineContent(position.line);
const indentation = getIndentation(lineContent, position.character);
if (isScalar(closestNode) && closestNode.value === null) {
return closestNode;
}
if (indentation === position.character) {
closestNode = this.getProperParentByIndentation(indentation, closestNode, textBuffer);
}
return closestNode;
}
private getProperParentByIndentation(indentation: number, node: YamlNode, textBuffer: TextBuffer): YamlNode {
if (!node) {
return this.internalDocument.contents as Node;
}
if (isNode(node) && node.range) {
const position = textBuffer.getPosition(node.range[0]);
if (position.character > indentation && position.character > 0) {
const parent = this.getParent(node);
if (parent) {
return this.getProperParentByIndentation(indentation, parent, textBuffer);
}
} else if (position.character < indentation) {
const parent = this.getParent(node);
if (isPair(parent) && isNode(parent.value)) {
return parent.value;
}
} else {
return node;
}
} else if (isPair(node)) {
const parent = this.getParent(node);
return this.getProperParentByIndentation(indentation, parent, textBuffer);
}
return node;
}
getParent(node: YamlNode): YamlNode | undefined {
return getParent(this.internalDocument, node);
}
}
/**
* Contains the SingleYAMLDocuments, to be passed
* to the `parseYAML` caller.
*/
export class YAMLDocument {
documents: SingleYAMLDocument[];
tokens: Token[];
private errors: YAMLDocDiagnostic[];
private warnings: YAMLDocDiagnostic[];
constructor(documents: SingleYAMLDocument[], tokens: Token[]) {
this.documents = documents;
this.tokens = tokens;
this.errors = [];
this.warnings = [];
}
}
interface YamlCachedDocument {
version: number;
parserOptions: ParserOptions;
document: YAMLDocument;
}
export class YamlDocuments {
// a mapping of URIs to cached documents
private cache = new Map<string, YamlCachedDocument>();
/**
* Get cached YAMLDocument
* @param document TextDocument to parse
* @param customTags YAML custom tags
* @param addRootObject if true and document is empty add empty object {} to force schema usage
* @returns the YAMLDocument
*/
getYamlDocument(document: TextDocument, parserOptions?: ParserOptions, addRootObject = false): YAMLDocument {
this.ensureCache(document, parserOptions ?? defaultOptions, addRootObject);
return this.cache.get(document.uri).document;
}
/**
* For test purpose only!
*/
clear(): void {
this.cache.clear();
}
private ensureCache(document: TextDocument, parserOptions: ParserOptions, addRootObject: boolean): void {
const key = document.uri;
if (!this.cache.has(key)) {
this.cache.set(key, { version: -1, document: new YAMLDocument([], []), parserOptions: defaultOptions });
}
const cacheEntry = this.cache.get(key);
if (
cacheEntry.version !== document.version ||
(parserOptions.customTags && !isArrayEqual(cacheEntry.parserOptions.customTags, parserOptions.customTags))
) {
let text = document.getText();
// if text is contains only whitespace wrap all text in object to force schema selection
if (addRootObject && !/\S/.test(text)) {
text = `{${text}}`;
}
const doc = parseYAML(text, parserOptions);
cacheEntry.document = doc;
cacheEntry.version = document.version;
cacheEntry.parserOptions = parserOptions;
}
}
}
export const yamlDocumentsCache = new YamlDocuments();
function YAMLErrorToYamlDocDiagnostics(error: YAMLError): YAMLDocDiagnostic {
return {
message: error.message,
location: {
start: error.pos[0],
end: error.pos[1],
toLineEnd: true,
},
severity: 1,
code: ErrorCode.Undefined,
};
}