read-conf
Version:
reads a config file
94 lines (91 loc) • 2.59 kB
JavaScript
var mergeOptions;
mergeOptions = require("merge-options");
module.exports = ({read, run, cleanUp, position}) => {
read.hookIn(position.after, (noop, o) => {
var arr, base, conf, hasDefault, i, iterate, len, mergeArgs, mergeConfig, obj, runners;
if (!o.state.cleaning) {
if ((iterate = o.iterate) != null) {
if (o.util.isString(iterate)) {
arr = o[iterate];
} else {
arr = iterate;
}
}
if (arr == null) {
arr = [{}];
} else if (!Array.isArray(arr)) {
arr = [arr];
}
o.bases = [];
o._cleanUps = [];
mergeConfig = {
concatArrays: o.concatArrays
};
mergeArgs = [o.raw, null];
if (hasDefault = (o.default != null)) {
mergeArgs.unshift(o.default);
}
if (o.assign != null) {
mergeArgs.push(o.assign);
}
runners = [];
for (i = 0, len = arr.length; i < len; i++) {
obj = arr[i];
mergeArgs[1 + hasDefault] = obj;
conf = mergeOptions.apply(mergeConfig, mergeArgs);
if (((base = o.base) != null) && typeof base === "function") {
base = base();
}
if (base == null) {
base = {};
}
base[o.prop || "config"] = conf;
base.readConfig = o;
base._readConfigIndex = o.bases.length;
o.bases.push(base);
runners.push(o.run(base));
}
return Promise.all(runners);
}
});
cleanUp.hookIn(position.before, (noop, o) => {
if ((o.cancel != null) && (o.bases != null) && o.state.running) {
return Promise.all(o.bases.map((tmpBase) => {
return o.cancel(tmpBase);
})).then(o.state.running);
}
});
run.hookIn(position.end - 1, async(base, o) => {
var e, val;
if ((o.cb != null) && !o.state.closing) {
try {
val = (await o.cb(base));
} catch (error) {
e = error;
if (o.watch) {
console.log(e);
o.cancel(base);
} else {
throw e;
}
}
if ((val != null) && typeof val === "function") {
return o._cleanUps.push(val);
}
}
});
return cleanUp.hookIn((noop, o) => {
var cleanUps;
if (((cleanUps = o._cleanUps) != null) && cleanUps.length > 0) {
return Promise.all(cleanUps).then((cleanUps) => {
return Promise.all(cleanUps.map((cleanUp) => {
if (typeof cleanUp === "function") {
return cleanUp();
}
}));
}).then(() => {
return o._cleanUps = null;
});
}
});
};