-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
65 lines (58 loc) · 1.77 KB
/
index.js
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
'use strict';
const yaml = require('yaml');
const recurse = require('reftools/lib/recurse.js').recurse;
function parseWithComments(str, commentProperty = '$comment') {
const ast = yaml.parseDocument(str);
recurse(ast,{},function(obj,key,state){
let comment;
if (obj[key] && obj[key].commentBefore) comment = obj[key].commentBefore;
if (obj[key] && obj[key].comment) comment = obj[key].comment;
if (comment && Array.isArray(state.parent)) {
let existing = state.parent.find(function(e,i,a){
if (e.key.value === commentProperty) return true;
return false;
});
if (existing) {
existing.value.value += '\n' + comment;
}
else {
state.parent.push(ast.createPair(commentProperty,comment.trim()));
}
}
});
return ast.toJSON();
}
function parseWithAliases(str) {
const aliases = new Map();
const ast = yaml.parseDocument(str);
yaml.visit(ast,function(key,node,path) {
if (yaml.isAlias(node)) {
aliases.set(node.source,node.toJS(ast));
}
});
return { data: ast.toJS(), aliases };
}
function stringifyWithComments(obj,commentProperty = '$comment') {
const ast = yaml.parseDocument(yaml.stringify(obj));
let parent = {};
let grandparent = {};
yaml.visit(ast,function(key,node,path) {
let kill = false;
if (yaml.isPair(node)) {
if (node.key.value === commentProperty) {
const comment = node.value.value;
grandparent.commentBefore = grandparent.commentBefore ? `${grandparent.commentBefore} ${node.value.value}` : ` ${node.value.value}`;
kill = true;
}
}
grandparent = parent;
parent = node;
if (kill) return yaml.visit.REMOVE;
});
return ast.toString();
}
module.exports = {
parseWithComments,
stringifyWithComments,
parseWithAliases
};