/
yaml.ts
189 lines (173 loc) · 6.82 KB
/
yaml.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
import { IndexToPosition } from '../parsing/text-utility';
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as yamlAst from "yaml-ast-parser";
import { JsonPath } from "./jsonpath";
import { Message, SourceLocation, Channel } from '../message';
import { NewEmptyObject } from "../parsing/stable-object";
/**
* reexport required elements
*/
export { newScalar } from "yaml-ast-parser";
export const Kind: { SCALAR: number, MAPPING: number, MAP: number, SEQ: number, ANCHOR_REF: number, INCLUDE_REF: number } = yamlAst.Kind;
export type YAMLNode = yamlAst.YAMLNode;
export type YAMLScalar = yamlAst.YAMLScalar;
export type YAMLMapping = yamlAst.YAMLMapping;
export type YAMLMap = yamlAst.YamlMap;
export type YAMLSequence = yamlAst.YAMLSequence;
export type YAMLAnchorReference = yamlAst.YAMLAnchorReference;
export const CreateYAMLMapping: (key: YAMLScalar, value: YAMLNode) => YAMLMapping = yamlAst.newMapping;
export const CreateYAMLScalar: (value: string) => YAMLScalar = yamlAst.newScalar;
export interface YAMLNodeWithPath {
path: JsonPath;
node: YAMLNode;
}
/**
* Parsing
*/
export function ParseToAst(rawYaml: string): YAMLNode {
return yamlAst.safeLoad(rawYaml, null) as YAMLNode;
}
export function* Descendants(yamlAstNode: YAMLNode, currentPath: JsonPath = [], deferResolvingMappings: boolean = false): Iterable<YAMLNodeWithPath> {
const todos: YAMLNodeWithPath[] = [{ path: currentPath, node: yamlAstNode }];
let todo: YAMLNodeWithPath | undefined;
while (todo = todos.pop()) {
// report self
yield todo;
// traverse
if (todo.node) {
switch (todo.node.kind) {
case Kind.MAPPING: {
let astSub = todo.node as YAMLMapping;
if (deferResolvingMappings) {
todos.push({ node: astSub.value, path: todo.path });
} else {
todos.push({ node: astSub.value, path: todo.path.concat([astSub.key.value]) });
}
}
break;
case Kind.MAP:
if (deferResolvingMappings) {
for (let mapping of (todo.node as YAMLMap).mappings) {
todos.push({ node: mapping, path: todo.path.concat([mapping.key.value]) });
}
} else {
for (let mapping of (todo.node as YAMLMap).mappings) {
todos.push({ node: mapping, path: todo.path });
}
}
break;
case Kind.SEQ: {
let astSub = todo.node as YAMLSequence;
for (let i = 0; i < astSub.items.length; ++i) {
todos.push({ node: astSub.items[i], path: todo.path.concat([i]) });
}
}
break;
}
}
}
}
export function ResolveAnchorRef(yamlAstRoot: YAMLNode, anchorRef: string): YAMLNodeWithPath {
for (let yamlAstNode of Descendants(yamlAstRoot)) {
if (yamlAstNode.node.anchorId === anchorRef) {
return yamlAstNode;
}
}
throw new Error(`Anchor '${anchorRef}' not found`);
}
/**
* Populates yamlNode.valueFunc with a function that creates a *mutable* object (i.e. no caching of the reference or such)
*/
function ParseNodeInternal(yamlRootNode: YAMLNode, yamlNode: YAMLNode, onError: (message: string, index: number) => void): () => any {
if (yamlNode.errors.length > 0) {
for (const error of yamlNode.errors) {
onError(`Syntax error: ${error.reason}`, error.mark.position);
}
return (yamlNode as any).valueFunc = () => null;
}
if ((yamlNode as any).valueFunc) {
return (yamlNode as any).valueFunc;
}
switch (yamlNode.kind) {
case Kind.SCALAR: {
const yamlNodeScalar = yamlNode as YAMLScalar;
return (yamlNode as any).valueFunc = yamlNodeScalar.valueObject !== undefined
? () => yamlNodeScalar.valueObject
: () => yamlNodeScalar.value;
}
case Kind.MAPPING:
onError("Syntax error: Encountered single mapping.", yamlNode.startPosition);
return (yamlNode as any).valueFunc = () => null;
case Kind.MAP: {
const factories: ([string, () => any])[] = [];
const yamlNodeMapping = yamlNode as YAMLMap;
for (const mapping of yamlNodeMapping.mappings) {
if (mapping.key.kind !== Kind.SCALAR) {
onError("Syntax error: Only scalar keys are allowed as mapping keys.", mapping.key.startPosition);
} else if (mapping.value === null) {
onError("Syntax error: No mapping value found.", mapping.key.endPosition);
} else {
factories.push([mapping.key.value, ParseNodeInternal(yamlRootNode, mapping.value, onError)]);
}
}
return (yamlNode as any).valueFunc = () => {
const result = NewEmptyObject();
for (const member of factories) {
result[member[0]] = member[1]();
}
return result;
};
}
case Kind.SEQ: {
const factories: (() => any)[] = [];
const yamlNodeSequence = yamlNode as YAMLSequence;
for (const item of yamlNodeSequence.items) {
factories.push(ParseNodeInternal(yamlRootNode, item, onError));
}
return (yamlNode as any).valueFunc = () => factories.map(f => f());
}
case Kind.ANCHOR_REF: {
const yamlNodeRef = yamlNode as YAMLAnchorReference;
return (ResolveAnchorRef(yamlRootNode, yamlNodeRef.referencesAnchor).node as any).valueFunc;
}
case Kind.INCLUDE_REF:
onError("Syntax error: INCLUDE_REF not implemented.", yamlNode.startPosition);
return (yamlNode as any).valueFunc = () => null;
default:
throw new Error("Unknown YAML node kind.");
}
}
export function ParseNode<T>(yamlNode: YAMLNode, onError: (message: string, index: number) => void = message => { throw new Error(message); }): T {
ParseNodeInternal(yamlNode, yamlNode, onError);
return (yamlNode as any).valueFunc();
}
export function CloneAst<T extends YAMLNode>(ast: T): T {
return ParseToAst(StringifyAst(ast)) as T;
}
export function StringifyAst(ast: YAMLNode): string {
return FastStringify(ParseNode<any>(ast));
}
export function Clone<T>(object: T): T {
return Parse<T>(FastStringify(object));
}
export function ToAst<T>(object: T): YAMLNode {
return ParseToAst(FastStringify(object));
}
export function Parse<T>(rawYaml: string, onError: (message: string, index: number) => void = message => { throw new Error(message); }): T {
const node = ParseToAst(rawYaml);
const result = ParseNode<T>(node, onError);
return result;
}
export function Stringify<T>(object: T): string {
return "---\n" + yamlAst.safeDump(object, { skipInvalid: true });
}
export function FastStringify<T>(obj: T): string {
try {
return JSON.stringify(obj, null, 1);
} catch (e) {
return Stringify(obj);
}
}