-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
112 lines (99 loc) · 3.4 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env node
const commander = require('commander');
const yaml = require('js-yaml');
const fs = require('fs');
const os = require('os');
const path = require('path');
const process = require('process');
const yamlinc = require('yaml-include');
generate = (def, generatorPath, output) => {
const generator = require(fs.realpathSync(generatorPath));
if (!generator) {
throw 'Could not require() ' + src;
}
const content = generator(def);
const target = output || src.replace(/\.[^.]*$/, ''); // strip final extension
content = content.replace(/\n/g, os.EOL);
const existing = fs.readFileSync(target, { encoding: 'utf8' });
if (existing === content) {
return 'upToDate';
}
else {
fs.writeFileSync(target, content, { encoding: 'utf8' });
return existing ? 'updated' : 'created';
}
}
if (require.main === module) {
commander
.usage('[options] <generator source file> ...')
.option('-d --def [def-file]', 'Definition file, parsed according to extension')
.option('-o --output [output-file]', 'Output file name; not valid with multiple generator sources')
.parse(process.argv);
if (commander.args.length < 1 || !commander.def || (commander.args.length > 1 && commander.output)) {
commander.outputHelp();
process.exitCode = 1;
}
else {
let def = fs.readFileSync(commander.def, { encoding: 'utf8' });
if (/\.json$/i.exec(commander.def)) {
def = JSON.parse(def);
}
else if (/\.ya?ml$/i.exec(commander.def)) {
const wd = process.cwd();
try {
process.chdir(path.dirname(commander.def));
def = yaml.safeLoad(def, { schema: yamlinc.YAML_INCLUDE_SCHEMA });
}
finally {
process.chdir(wd);
}
}
for (const src of commander.args) {
const generator = require(fs.realpathSync(src));
if (!generator) {
console.error('Could not require() ' + src);
process.exitCode = 1;
break;
}
let content;
try {
content = generator(def);
}
catch (err) {
console.error(err);
process.exitCode = 1;
break;
}
const target = commander.output || src.replace(/\.[^.]*$/, ''); // strip final extension
content = content.replace(/\n/g, os.EOL);
let existing;
try {
existing = fs.readFileSync(target, { encoding: 'utf8' });
}
catch (err) {
if (err.code !== 'ENOENT') {
console.warn(err);
}
}
if (existing === content) {
console.log(`${target} is up to date`);
}
else {
if (existing) {
console.log(`${target} is out of date, updating`);
}
else {
console.log(`creating ${target}`);
}
try {
fs.writeFileSync(target, content, { encoding: 'utf8' });
}
catch (err) {
console.error(err);
process.exitCode = 1;
break;
}
}
}
}
}