-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInlineYAML.hx
74 lines (59 loc) · 1.67 KB
/
InlineYAML.hx
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
import sys.io.File;
import haxe.ds.StringMap;
class InlineYAML {
static function main() : Int {
var args = Sys.args();
if (args == null || args.length < 2) {
Sys.println("Error: expected 2 args but got less. example: inline-ymal in out");
return 1;
}
var text = File.getContent(args[0]);
var inliner = new InlineYAML();
var inlinedText = inliner.inlineText(text);
File.saveContent(args[1], inlinedText);
return 0;
}
public function new() {}
function inlineText(text : String) : String {
var lines = text.split("\n");
var reg = ~/(.+): (.+)/;
var pairs = new StringMap<String>();
for (line in lines) {
if (reg.match(line)) {
pairs.set(StringTools.trim(reg.matched(1)), StringTools.trim(reg.matched(2)));
}
}
reg = ~/\{\{([\w-]*)\}\}/g;
var changed : Bool = true;
while (changed) {
changed = false;
for (key in pairs.keys()) {
var value = pairs.get(key);
var newVal = inlineVars(value, pairs, reg);
if (newVal != null) {
pairs.set(key, newVal);
changed = true;
}
}
}
var inlinedText = "";
for (key in pairs.keys()) {
var value = pairs.get(key);
inlinedText += '$key: $value\n';
}
return inlinedText;
}
inline function inlineVars(value : String, usingMap : StringMap<String>, reg : EReg) : String {
var result : String = value;
var newVal = reg.map(value, function(r) : String {
var match = r.matched(1);
var resultVal = usingMap.get(match);
if (resultVal == null) {
resultVal = r.matched(0);
Sys.println('Warning: can\'t find value for key: \'$match\' used in $value');
}
return resultVal;
});
return result != newVal ? newVal : null;
}
}