-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.js
63 lines (48 loc) · 1.69 KB
/
main.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
const _ = require('lodash');
const Promise = require('bluebird');
const readFile = Promise.promisify(require('fs').readFile);
const writeFile = Promise.promisify(require('fs').writeFile);
const spyables = require('./js/spyables');
const config = require('./main.config');
const LogDiff = require('./js/LogDiff');
let handleError = (err, cli) => {
if (cli) {
console.error(err.message);
process.exit(1);
}
return Promise.reject(err);
};
let envsub = (raw = {}) => {
let templateContents, outputContents;
raw.command = raw.command /* istanbul ignore next */ || 'envsub';
let args = _.merge({}, {outputFile: null, options: config[raw.command].DEFAULT_OPTIONS, cli: false}, raw);
if (args.templateFile == null) {
return handleError(Error(`${args.command} templateFile outputFile - missing args`), args.cli);
}
args.outputFile = args.outputFile || args.templateFile;
return readFile(args.templateFile, 'utf8').then((contents) => {
templateContents = contents;
let parse = require(`./js/${args.command}-parser`);
outputContents = parse(templateContents, args);
if (args.options.diff) LogDiff.logDiff(templateContents, outputContents);
if (args.outputFile === 'stdout') {
return new Promise((resolve) => {
spyables.writeToStdout(outputContents);
resolve();
});
} else {
return writeFile(args.outputFile, outputContents);
}
}).then(() => {
if (args.cli) process.exit(0);
return Promise.resolve({
templateFile: args.templateFile,
templateContents,
outputFile: args.outputFile,
outputContents
});
}).catch((err) => {
return handleError(err, args.cli);
});
};
module.exports = envsub;