-
Notifications
You must be signed in to change notification settings - Fork 23
/
yamlParser.ts
322 lines (261 loc) · 10.8 KB
/
yamlParser.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Copyright (c) Adam Voss. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { ASTNode, BooleanASTNode, NullASTNode, ArrayASTNode, NumberASTNode, ObjectASTNode, PropertyASTNode, StringASTNode, JSONDocument } from './jsonParser';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
import * as Yaml from 'yaml-ast-parser'
import { Schema, Type } from 'js-yaml';
import { getLineStartPositions, getPosition, ILineColumn } from '../utils/documentPositionCalculator'
export interface YAMLError {
getMessage: () => string;
start: number;
end: number;
}
export class SingleYAMLDocument extends JSONDocument {
private lines : number[];
public root: ASTNode;
public errors: YAMLError[];
public warnings: YAMLError[];
constructor(lines: number[]) {
super(null, []);
this.lines = lines;
this.root = null;
this.errors = [];
this.warnings = [];
}
public getNodeFromOffset(offset: number): ASTNode {
return this.getNodeFromOffsetEndInclusive(offset);
}
public getNodeByIndent = (lines: number[], offset: number, node: ASTNode): ASTNode => {
const offsetPosition: ILineColumn = getPosition(offset, this.lines);
function findNode(children: ASTNode[]): ASTNode {
for (var idx: number = 0; idx < children.length; idx++) {
const child: ASTNode = children[idx];
const childPosition: ILineColumn = getPosition(child.start, lines);
if (childPosition.column > offsetPosition.column) {
return null;
}
const foundNode: ASTNode = findNode(child.getChildNodes());
if (foundNode) {
return foundNode;
}
// We have the right indentation, need to return based on line
if (childPosition.line == offsetPosition.line) {
return child;
}
if (childPosition.line > offsetPosition.line) {
// Get previous
(idx - 1) >= 0 ? children[idx - 1] : child;
}
// Else continue loop to try next element
}
// Special case, we found the correct
return children[children.length - 1];
}
return findNode(node.getChildNodes()) || node;
}
}
function recursivelyBuildAst(parent: ASTNode, node: Yaml.YAMLNode): ASTNode {
if (!node) {
return;
}
switch (node.kind) {
case Yaml.Kind.MAP: {
const instance = <Yaml.YamlMap>node;
const result = new ObjectASTNode(parent, null, node.startPosition, node.endPosition);
addPropertiesToObjectNode(result, instance.mappings);
return result;
}
case Yaml.Kind.MAPPING: {
const instance = <Yaml.YAMLMapping>node;
const key = instance.key;
// Technically, this is an arbitrary node in YAML
// I doubt we would get a better string representation by parsing it
const keyNode = new StringASTNode(null, null, true, key.startPosition, key.endPosition);
keyNode.value = key.value;
const result = new PropertyASTNode(parent, keyNode);
result.end = instance.endPosition;
const valueNode = (instance.value) ? recursivelyBuildAst(result, instance.value) : new NullASTNode(parent, key.value, instance.endPosition, instance.endPosition);
valueNode.location = key.value;
result.setValue(valueNode);
return result;
}
case Yaml.Kind.SEQ: {
const instance = <Yaml.YAMLSequence>node;
const result = new ArrayASTNode(parent, null, instance.startPosition, instance.endPosition);
addItemsToArrayNode(result, instance.items);
return result;
}
case Yaml.Kind.SCALAR: {
const instance = <Yaml.YAMLScalar>node;
const type = Yaml.determineScalarType(instance)
// The name is set either by the sequence or the mapping case.
const name = null;
const value = instance.value;
//This is a patch for redirecting values with these strings to be boolean nodes because its not supported in the parser.
let possibleBooleanValues = ['y', 'Y', 'yes', 'Yes', 'YES', 'n', 'N', 'no', 'No', 'NO', 'on', 'On', 'ON', 'off', 'Off', 'OFF'];
if (possibleBooleanValues.indexOf(value.toString()) !== -1) {
return new BooleanASTNode(parent, name, value, node.startPosition, node.endPosition)
}
switch (type) {
case Yaml.ScalarType.null: {
return new StringASTNode(parent, name, false, instance.startPosition, instance.endPosition);
}
case Yaml.ScalarType.bool: {
return new BooleanASTNode(parent, name, Yaml.parseYamlBoolean(value), node.startPosition, node.endPosition)
}
case Yaml.ScalarType.int: {
const result = new NumberASTNode(parent, name, node.startPosition, node.endPosition);
result.value = Yaml.parseYamlInteger(value);
result.isInteger = true;
return result;
}
case Yaml.ScalarType.float: {
const result = new NumberASTNode(parent, name, node.startPosition, node.endPosition);
result.value = Yaml.parseYamlFloat(value);
result.isInteger = false;
return result;
}
case Yaml.ScalarType.string: {
const result = new StringASTNode(parent, name, false, node.startPosition, node.endPosition);
result.value = node.value;
return result;
}
}
break;
}
case Yaml.Kind.ANCHOR_REF: {
const instance = (<Yaml.YAMLAnchorReference>node).value
return recursivelyBuildAst(parent, instance) ||
new NullASTNode(parent, null, node.startPosition, node.endPosition);
}
case Yaml.Kind.INCLUDE_REF: {
const result = new StringASTNode(parent, null, false, node.startPosition, node.endPosition);
result.value = node.value;
return result;
}
}
}
// These two helper functions exist to add support for compile-time expressions.
// Basically, they just hoist the entries under the expression to its parent
// and remove the expression from the parsed YAML.
function addPropertiesToObjectNode(node: ObjectASTNode, properties: Yaml.YAMLMapping[]): void {
for (const property of properties) {
// The endsWith check is necessary because you can have dynamically-generated variables;
// for example, ${{ environment }}Release: true.
if (property.key.value.startsWith("${{") && property.key.value.endsWith("}}")) {
// Ensure we have a value (object) _and_ that the value has mappings (properties).
if (property.value?.mappings !== undefined) {
addPropertiesToObjectNode(node, property.value.mappings);
}
} else {
node.addProperty(<PropertyASTNode>recursivelyBuildAst(node, property));
}
}
}
function addItemsToArrayNode(node: ArrayASTNode, items: Yaml.YAMLNode[]): void {
let count = 0;
for (const item of items) {
// TODO: What the heck is this check
if (item === null && count === items.length - 1) {
break;
}
let itemNode: ASTNode;
if (item === null) {
// Be aware of https://github.com/nodeca/js-yaml/issues/321
// Cannot simply work around it here because we need to know if we are in Flow or Block
itemNode = new NullASTNode(node.parent, null, node.end, node.end);
} else {
if (item.kind === Yaml.Kind.MAP &&
item.mappings[0].key.value.startsWith("${{") &&
item.mappings[0].key.value.endsWith("}}")) {
const value = item.mappings[0].value;
if (value === null) {
continue;
}
if (value.kind === Yaml.Kind.SEQ) {
// e.g. conditionally adding steps to a job.
addItemsToArrayNode(node, item.mappings[0].value.items);
count++;
continue;
} else if (value.kind === Yaml.Kind.MAP) {
// e.g. looping through a stepList parameter and checking each value.
// NOTE: We don't have a great story for this as we can't validate
// the resulting ${{ pair.key }}: ${{ pair.value }} against the schema,
// so we currently just create an empty object with no properties.
// We might need to revisit this if we start providing LSP capabilities
// for expressions.
itemNode = recursivelyBuildAst(node, value);
} else {
throw new Error(`Unexpected kind ${value.kind}`);
}
} else {
itemNode = recursivelyBuildAst(node, item);
}
}
itemNode.location = node.items.length;
node.addItem(itemNode);
count++;
}
}
function convertError(e: Yaml.YAMLException): YAMLError {
return { getMessage: () => e.reason, start: e.mark.position, end: e.mark.position + e.mark.column };
}
function createJSONDocument(yamlNode: Yaml.YAMLNode, startPositions: number[], text: string): SingleYAMLDocument {
let _doc: SingleYAMLDocument = new SingleYAMLDocument(startPositions);
_doc.root = recursivelyBuildAst(null, yamlNode);
if (!_doc.root) {
// TODO: When this is true, consider not pushing the other errors.
_doc.errors.push({ getMessage: () => localize('Invalid symbol', 'Expected a YAML object, array or literal'), start: yamlNode.startPosition, end: yamlNode.endPosition } );
}
const duplicateKeyReason: string = 'duplicate key';
//Patch ontop of yaml-ast-parser to disable duplicate key message on merge key
let isDuplicateAndNotMergeKey = function (error: Yaml.YAMLException, yamlText: string) {
let errorConverted: YAMLError = convertError(error);
let errorStart: number = errorConverted.start;
let errorEnd: number = errorConverted.end;
if (error.reason === duplicateKeyReason && yamlText.substring(errorStart, errorEnd).startsWith("<<")) {
return false;
}
return true;
};
const errors: YAMLError[] = yamlNode.errors.filter(e => e.reason !== duplicateKeyReason && !e.isWarning).map(e => convertError(e));
const warnings: YAMLError[] = yamlNode.errors.filter(e => (e.reason === duplicateKeyReason && isDuplicateAndNotMergeKey(e, text)) || e.isWarning).map(e => convertError(e));
errors.forEach(e => _doc.errors.push(e));
warnings.forEach(e => _doc.warnings.push(e));
return _doc;
}
export class YAMLDocument {
public documents: SingleYAMLDocument[]
public errors: YAMLError[];
public warnings: YAMLError[];
constructor(documents: SingleYAMLDocument[]) {
this.documents = documents;
this.errors = [];
this.warnings = [];
}
}
export function parse(text: string, customTags = []): YAMLDocument {
const startPositions = getLineStartPositions(text)
// This is documented to return a YAMLNode even though the
// typing only returns a YAMLDocument
const yamlDocs = []
let schemaWithAdditionalTags = Schema.create(customTags.map((tag) => {
const typeInfo = tag.split(' ');
return new Type(typeInfo[0], { kind: typeInfo[1] || 'scalar' });
}));
//We need compiledTypeMap to be available from schemaWithAdditionalTags before we add the new custom properties
customTags.map((tag) => {
const typeInfo = tag.split(' ');
schemaWithAdditionalTags.compiledTypeMap[typeInfo[0]] = new Type(typeInfo[0], { kind: typeInfo[1] || 'scalar' });
});
let additionalOptions: Yaml.LoadOptions = {
schema: schemaWithAdditionalTags
}
Yaml.loadAll(text, doc => yamlDocs.push(doc), additionalOptions);
return new YAMLDocument(yamlDocs.map(doc => createJSONDocument(doc, startPositions, text)));
}