-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
94 lines (88 loc) · 2.8 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
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
var util = require("util")
var glob = require("glob");
var fs = require("fs");
var path = require("path");
var createBranch = require("organic-dna-branches").createBranch
var selectBranch = require("organic-dna-branches").selectBranch
var YAML = require("yaml")
module.exports.loadDir = function(dna, dirPath, namespace, callback) {
if(typeof namespace == "function") {
callback = namespace;
namespace = "";
}
dirPath = path.normalize(dirPath);
glob(dirPath+"/**/*.@(json|yaml|yml)", function(err, files){
if(err) return callback(err)
var filesLeft = files.length;
if(filesLeft == 0)
return callback()
files.forEach(function(file){
file = path.normalize(file);
// append namespace tail from file path
// tail is in form X.Y.Z where '.' are path delimiters
var target = file.replace(dirPath+path.sep, "")
.replace(".json", "")
.replace(".yaml", "")
.replace(".yml", "")
.replace(/\//g, ".")
.replace(/\\/g, ".");
if(namespace != "")
target = namespace+"."+target; // insert '.' as namespace should be in form X.Y.Z without trailing '.'
// load file data at given namespaced branch
module.exports.loadFile(dna, file, target, function(err){
if(err) return callback(err)
filesLeft -= 1;
if(filesLeft == 0)
callback();
});
});
});
}
module.exports.loadFile = function(dna, filePath, namespace, callback){
if(typeof namespace == "function") {
callback = namespace;
namespace = "";
}
fs.readFile(filePath, function(err, data){
if(err) return callback(err)
data = data.toString();
try {
switch(path.extname(filePath)) {
case '.json':
data = JSON.parse(data);
break
case '.yaml':
case '.yml':
let parsed = null
parsed = YAML.parseAllDocuments(data)
parsed = parsed.map(function (item) {
if (item.errors && item.errors.length > 0) {
throw item.errors[0]
}
return item.toJSON()
})
if (parsed.length === 1) parsed = parsed[0]
data = parsed
break
}
}catch(e) {
return callback(new Error("Failed to parse " + filePath + " given error: " + e.message))
}
/*
quick merge into existing nodes
useful for having the configuration per namespace/branch split
into .yaml and .json files
*/
try {
let existing = selectBranch(dna, namespace)
if (typeof existing === 'object') {
data = Object.assign({}, existing, data)
}
} catch (nonExistingNamespaceErr) {
// ignore non existing branch errors
// createBranch is going create the namespace path anyway
}
createBranch(dna, namespace, data);
callback();
});
}