-
Notifications
You must be signed in to change notification settings - Fork 1
/
process-template-tree.js
59 lines (53 loc) · 1.81 KB
/
process-template-tree.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
const path = require('path');
const fs = require('fs');
const sh = require('shelljs');
const ejs = require('ejs');
const debug = require('debug')('template-tree-processor');
const logger = require('../logger')('template-tree-processor');
async function processDirectory(node, targetPath, replacers) {
debug('Processing dir', node.path, 'for target', targetPath);
sh.mkdir(targetPath); // create the directory (pretty much self-explanatory)
logger.success('Created the directory:', targetPath);
await Promise.all(
node.children.map(
async child =>
await processTemplateTree(
child,
path.join(targetPath, child.name),
replacers
) // process the child node
)
);
}
async function processFile(node, targetPath, replacers) {
debug('Processing file', node.path, 'for target', targetPath);
if (node.extension === '.ejs') {
let targetPathWithoutEJSExtension = targetPath.substr(
0,
targetPath.length - node.extension.length
);
fs.writeFileSync(
targetPathWithoutEJSExtension,
await ejs.renderFile(node.path, replacers)
); // Render the template into the target path (without the .ejs extension)
logger.success('Created the file:', targetPathWithoutEJSExtension);
} else {
sh.cp(node.path, targetPath);
logger.success('Created the file:', targetPath);
}
}
/**
* Processes a node in the file tree
* @param node A node in the file tree
* @param targetPath the (raw) path (including the original extension) of the target. `.ejs` gets stripped internally
* @param replacers
* @return {Promise<void>}
*/
async function processTemplateTree(node, targetPath, replacers) {
if (node.type === 'directory') {
await processDirectory(node, targetPath, replacers);
} else if (node.type === 'file') {
await processFile(node, targetPath, replacers);
}
}
module.exports = processTemplateTree;