-
-
Notifications
You must be signed in to change notification settings - Fork 209
/
generator.js
366 lines (326 loc) · 10.5 KB
/
generator.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
const os = require('os');
const path = require('path');
const fs = require('fs');
const Handlebars = require('handlebars');
const _ = require('lodash');
const randomName = require('project-name-generator');
const xfs = require('fs.extra');
const beautifier = require('./beautifier');
const registerPartial = require('./register-partial');
const parse = require('./parser');
const generator = module.exports;
/**
* Renders the content of a file and outputs it.
*
* @private
* @param {String} filePath Path to the file you want to render.
* @param {String} data Data to pass the template during rendering.
* @return {Promise}
*/
const renderFile = (filePath, data) => new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, content) => {
if (err) return reject(err);
try {
const template = Handlebars.compile(content);
const parsed_content = template(data);
resolve(parsed_content);
} catch (e) {
reject(e);
}
});
});
/**
* Generates a file.
*
* @private
* @param {Object} options
* @param {String} options.templates_dir Directory where the templates live.
* @param {String} options.target_dir Directory where the file will be generated.
* @param {String} options.file_name Name of the generated file.
* @param {String} options.root Root directory.
* @param {Object} options.data Data to pass to the template.
* @return {Promise}
*/
const generateFile = options => new Promise((resolve, reject) => {
const templates_dir = options.templates_dir;
const target_dir = options.target_dir;
const file_name = options.file_name;
const root = options.root;
const data = options.data;
renderFile(path.resolve(root, file_name), data)
.then((parsed_content) => {
const template_path = path.relative(templates_dir, path.resolve(root, file_name));
const generated_path = path.resolve(target_dir, template_path);
fs.writeFile(generated_path, parsed_content, 'utf8', (err) => {
if (err) return reject(err);
resolve();
});
})
.catch(reject);
});
/**
* Generates a file for every topic.
*
* @param config
* @param topic
* @param topicName
* @returns {Promise}
*/
const generateTopicFile = (config, topic, topicName) => new Promise((resolve, reject) => {
fs.readFile(path.join(config.root, config.file_name), 'utf8', (err, data) => {
if (err) return reject(err);
const subdir = config.root.replace(new RegExp(`${config.templates_dir}[/]?`),'');
const new_filename = config.file_name.replace('$$topic$$', topicName);
const target_file = path.resolve(config.target_dir, subdir, new_filename);
const template = Handlebars.compile(data.toString());
const content = template({
openbrace: '{',
closebrace: '}' ,
topicName: topicName.replace(/[}{]/g, ''),
topic,
asyncapi: config.data.asyncapi
});
fs.writeFile(target_file, content, 'utf8', (err) => {
if (err) return reject(err);
resolve();
});
});
});
/**
* Generates all the files for each topic.
*
* @param {Object} config Configuration options
* @returns {Promise}
*/
const generateTopicFiles = options => new Promise((resolve, reject) => {
let shouldResolve = true;
_.each(options.data.asyncapi.topics, (topic, topicName) => {
generateTopicFile(options, topic, topicName).catch((err) => {
shouldResolve = false;
reject(err);
});
});
if (shouldResolve) resolve();
});
/**
* Generates the directory structure.
*
* @private
* @param {Object} config Configuration options
* @param {Object|String} config.asyncapi AsyncAPI JSON or a string pointing to a AsyncAPI file.
* @param {String} config.target_dir Absolute path to the directory where the files will be generated.
* @param {String} config.templates Absolute path to the templates that should be used.
* @return {Promise}
*/
const generateDirectoryStructure = config => new Promise((resolve, reject) => {
const target_dir = config.target_dir;
const templates_dir = config.templates;
xfs.mkdirpSync(target_dir);
const walker = xfs.walk(templates_dir, {
followLinks: false
});
walker.on('file', async (root, stats, next) => {
try {
if (stats.name.includes('$$topic$$')) {
// this file should be handled for each in asyncapi.paths
await generateTopicFiles({
root,
templates_dir,
target_dir,
data: config,
file_name: stats.name
});
const template_path = path.relative(templates_dir, path.resolve(root, stats.name));
fs.unlink(path.resolve(target_dir, template_path), next);
} else {
const file_path = path.relative(templates_dir, path.resolve(root, stats.name));
if (!file_path.startsWith('.partials/') && !file_path.startsWith('.helpers/')) {
// this file should only exist once.
await generateFile({
root,
templates_dir,
target_dir,
data: config,
file_name: stats.name
});
}
next();
}
} catch (e) {
reject(e);
}
});
walker.on('directory', async (root, stats, next) => {
try {
const dir_path = path.resolve(target_dir, path.relative(templates_dir, path.resolve(root, stats.name)));
if (stats.name !== '.partials' && stats.name !== '.helpers') xfs.mkdirpSync(dir_path);
next();
} catch (e) {
reject(e);
}
});
walker.on('errors', (root, nodeStatsArray) => {
reject(nodeStatsArray);
});
walker.on('end', async () => {
resolve();
});
});
/**
* Register the template partials
*
* @private
* @param {Object} config Configuration options
* @param {String} config.templates Absolute path to the templates that should be used.
* @return {Promise}
*/
const registerHelpers = config => new Promise((resolve, reject) => {
const helpers_dir = path.resolve(config.templates, '.helpers');
if (!fs.existsSync(helpers_dir)) return resolve();
const walker = xfs.walk(helpers_dir, {
followLinks: false
});
walker.on('file', async (root, stats, next) => {
try {
const file_path = path.resolve(config.templates, path.resolve(root, stats.name));
require(file_path);
next();
} catch (e) {
reject(e);
}
});
walker.on('errors', (root, nodeStatsArray) => {
reject(nodeStatsArray);
});
walker.on('end', async () => {
resolve();
});
});
/**
* Register the template helpers
*
* @private
* @param {Object} config Configuration options
* @param {String} config.templates Absolute path to the templates that should be used.
* @return {Promise}
*/
const registerPartials = config => new Promise((resolve, reject) => {
const partials_dir = path.resolve(config.templates, '.partials');
if (!fs.existsSync(partials_dir)) return resolve();
const walker = xfs.walk(partials_dir, {
followLinks: false
});
walker.on('file', async (root, stats, next) => {
try {
const file_path = path.resolve(config.templates, path.resolve(root, stats.name));
await registerPartial(file_path);
next();
} catch (e) {
reject(e);
}
});
walker.on('errors', (root, nodeStatsArray) => {
reject(nodeStatsArray);
});
walker.on('end', () => {
resolve();
});
});
const bundleAndApplyDefaults = config => new Promise((resolve, reject) => {
parse(config.asyncapi)
.then((asyncapi) => {
config.asyncapi = beautifier(asyncapi);
const random_name = randomName().dashed;
if (!config.template) {
return reject(new Error('No template has been specified.'));
}
_.defaultsDeep(config, {
asyncapi: {
info: {
title: random_name
}
},
package: {
name: _.kebabCase(_.result(config, 'asyncapi.info.title', random_name))
},
target_dir: path.resolve(os.tmpdir(), 'asyncapi-generated'),
templates: path.resolve(__dirname, '../templates')
});
config.templates = `${config.templates}/${config.template}`;
resolve(config);
})
.catch(reject);
});
/**
* Outputs the result of compiling a template.
*
* @module generator.generate
* @param {Object} config Configuration options
* @param {Object|String} config.asyncapi AsyncAPI JSON or a string pointing to an AsyncAPI file.
* @param {String} config.target_dir Path to the directory where the files will be generated.
* @return {Promise}
*/
generator.generate = config => new Promise((resolve, reject) => {
bundleAndApplyDefaults(config)
.then((cfg) => {
async function start () {
await registerHelpers(cfg);
await registerPartials(cfg);
await generateDirectoryStructure(cfg);
}
start().then(resolve).catch(reject);
})
.catch(reject);
});
/**
* Generates a file in a given template.
*
* @param {object} options
* @param {string} [templatesDir] Directory where templates are located. Defaults to internal template directory.
* @param {string} template Name of the template to use.
* @param {string} file Path to the template file you want to generate.
* @param {object} config Configuration options.
* @param {string|object} asyncapi An AsyncAPI definition.
* @return {Promise<string, Error>} A promise that resolves with the generated content.
*/
generator.generateTemplateFile = ({
templatesDir = path.resolve(__dirname, '../templates'),
template,
file,
config,
}) => new Promise((resolve, reject) => {
bundleAndApplyDefaults({
...config,
...{
template,
}
})
.then((cfg) => {
async function start () {
await registerHelpers(cfg);
await registerPartials(cfg);
return renderFile(path.resolve(templatesDir, template, file), cfg);
}
return start().then(resolve).catch(reject);
})
.catch(reject);
});
/**
* Reads the content of a file in a given template.
*
* @param {object} options
* @param {string} [templatesDir] Directory where templates are located. Defaults to internal template directory.
* @param {string} template Name of the template to use.
* @param {string} file Path to the template file you want to generate.
* @return {Promise<string, Error>} A promise that resolves with the generated content.
*/
generator.getTemplateFile = ({
templatesDir = path.resolve(__dirname, '../templates'),
template,
file,
}) => new Promise((resolve, reject) => {
fs.readFile(path.resolve(templatesDir, template, file), 'utf8', (err, content) => {
if (err) return reject(err);
resolve(content);
});
});