Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·205 lines (168 loc) · 5.93 KB
/
Copy pathindex.js
File metadata and controls
executable file
·205 lines (168 loc) · 5.93 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env node
const fs = require('fs-extra');
const _ = require('lodash')
const yaml = require('js-yaml');
const Promise = require('bluebird');
const marked = require('marked');
Promise.promisifyAll(fs);
_.templateSettings.interpolate = /<%=([\s\S]+?)%>/g; // disable ES6 ${...} syntax, which may be used in JS intended for browser
const doExports = () => {
module.exports.makeRecurse = makeRecurse;
module.exports.gulp = makeGulpPlugin;
}
const main = () => {
const program = require('commander');
const path = require('path');
const glob = require('glob-all');
program
.option('-c, --content <path>', '(REQUIRED) YAML/JSON content file')
.option('-t, --templates <path>', '(REQUIRED) directory (recursively) containing template files')
.option('-o, --out <path>', '(REQUIRED) output directory')
.option('-s, --static <path>', '(optional) directory (recursively) containing static files to copy to output directory')
.parse(process.argv);
_.each(['content','templates','out'], (x) => {
if (!program[x]) {
log(`ERROR: Option required: --${x}`);
program.help(); // exits
}
});
const content = loadContent(program.content);
fs.emptyDirSync(program.out);
if (program.static) {
fs.copySync(program.static, program.out);
}
const templateFilenames = glob.sync(program.templates + '/**/*');
const templatesByName = _.fromPairs(_.map(templateFilenames, (f) => {
const name = getTemplateNameFromFilepath(f);
return [name, _.template(fs.readFileSync(f, 'utf8'))]; // TODO: async
}));
const writeOutputFile = (filepath, text) => fs.outputFileSync(path.join(program.out, filepath), text);
const meta = {};
_.each(content, makeRecurse(templatesByName, writeOutputFile, meta));
const error = makeAnyFinalError(meta);
if (error) throw error;
}
const makeGulpPlugin = (content) => {
const through = require('through2');
const Vinyl = require('vinyl');
if (!content) throw new Error("You need content!");
if (_.isString(content)) {
content = loadContent(content);
} else
if (!_.isArray(content)) {
throw new Error("content must be either a string (yaml filename) or an array (loaded content, as from a yaml file)");
}
const templatesByName = {};
const outputFiles = [];
return through.obj(
(file, encoding, callback) => {
const name = getTemplateNameFromFilepath(file.path);
templatesByName[name] = _.template(file.contents.toString(encoding), { sourceURL:file.path });
callback();
},
function (callback) { // flush
const generateOutputFile = (filepath, text) => this.push(
new Vinyl({ path:filepath, contents:Buffer.from(text, 'utf8') }));
try {
const meta = {};
_.each(content, makeRecurse(templatesByName, generateOutputFile, meta));
callback(makeAnyFinalError(meta));
} catch (e) {
callback(e);
}
}
);
}
const loadContent = filename => {
log("loadContent:", filename);
const content = yaml.safeLoad(fs.readFileSync(filename, 'utf8'));
const recurse = x =>
_.isArray(x) ? _.map(x, recurse) :
_.isPlainObject(x) ?
x.$globals ? ( _.assign(globalsByName, x.$globals), null ) :
x.$include ? loadContent(x.$include) :
_.mapValues(x, recurse) :
x;
return recurse(content);
// return _.tap(recurse(content), x=>log(JSON.stringify(x,0,2)));
}
const makeAnyFinalError = meta => (meta.errors && !process.env.DEBUG) && new Error("Got errors, check error log (Set $DEBUG to emit errors into output files and finish with success anyway)")
const getTemplateNameFromFilepath = (filepath) =>
/.*\/([^.]+).*/.exec(filepath)[1]; // TODO: nest template naming (flattening here)
const makeRecurse = (templatesByName, onOutputFile, meta={}) => {
const recurse = (os) => {
if (os == null) { os = []; }
if (!_.isArray(os)) { os = [os]; }
// log('recurse', os.length);
return _.map(os, (o) => {
let text;
try {
if (_.isPlainObject(o)) {
if (o.$ref) {
o = globalsByName[o.$ref];
}
if (o.$globals) { // loaded in code above
return null; // TODO: this is hacky: silently ignored unless at root, no scoping, etc.
} else
if (o.$object) {
if (o.$t) { throw new Error("object can't have both $object and $t"); } // TODO: show path into content
// used for making yaml references
return null;
} else
if (!o.$t) { throw new Error("Content object lacks $t"); } // TODO: show path into content
const template = templatesByName[o.$t];
if (!template) { throw new Error("No template for $t: "+o.$t); } // TODO: show path into content
text = template(_.assign({
$:{ recurse:recurse },
_:_,
}, o), {sourceURL:o.$t});
if (o.$path) {
onOutputFile(o.$path, text);
}
} else
if (_.isArray(o)) {
text = recurse(o); // flatten nested arrays; TODO really?
}
else {
o = (''+o);
text = marked(o);
const m = /^<p>([^]*)<\/p>\n$/ .exec(text);
if (m && !/<p>/.test(m[1])) {
// Only 1 wrapping <p>: replace with <span>
text = `<span>${m[1]}</span>`;
}
}
} catch(e) {
text = makeErrorText(e);
console.error(e);
if (!meta.errors) meta.errors=[];
meta.errors.push(e);
}
return text;
}).join('\n');
}
recurse.meta = meta; // heh
return recurse;
}
const globalsByName = {};
const makeErrorText = e => `
<div
class="x-temple-error"
style="
background-color:#a00;
color:white;
font-family:monospace;
font-size=120%;
padding:10px;
border: 4px dashed #f33;
border-radius: 8px;
"
>
${e}
</div>`
const log = console.log;
if (require.main === module) {
main();
} else {
doExports();
}