-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlazy-generate.js
105 lines (77 loc) · 2.44 KB
/
lazy-generate.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
#!/usr/bin/env node
/*jshint esversion: 6 */
'use strict';
const consolidate = require('consolidate');
const fs = require('fs');
const program = require('commander');
const cwd = process.cwd();
console.log('\n lazy generate\n');
if (!fs.existsSync(`${cwd}/.lazy`)) {
console.log(` Lazy project folder not found, please execute: lazy init`);
process.exit(1);
}
const lazySettings = JSON.parse(fs.readFileSync(`${cwd}/.lazy/lazy-settings.json`));
program.parse(process.argv);
if (!program.args.length) {
console.error(' ERROR - template required');
process.exit(1);
}
const template = program.args[0];
const templateArgs = program.args.slice(1);
let templatePath = `${cwd}/.lazy/templates/${template}`;
let templateSettings = require(`${templatePath}/template-settings.js`);
if (templateArgs.lentgh < templateSettings.inputs.length) {
console.error(' ERROR - Missing template arguments');
let inputs = '';
templateSettings.inputs.forEach(input => {
inputs += `[${input}]`;
});
console.error(` lazy generate ${template} ${inputs}`)
process.exit(1);
}
let inputs = {};
for (let key in templateSettings.inputs) {
inputs[templateSettings.inputs[key]] = templateArgs[key];
}
let outputs = {};
for (let file in templateSettings.outputs) {
let output = templateSettings.outputs[file];
let outputPath = '';
if (typeof output == 'function') {
outputPath = output(inputs);
} else {
outputPath = output;
for (let input in inputs) {
outputPath = outputPath.replace(`%{${input}}`, inputs[input]);
}
}
outputs[file] = outputPath;
}
for (let file in outputs) {
let output = outputs[file];
console.log(` Creating ${file} to ${output}`);
let path = '';
let directories = output.split("/");
directories.slice(0, directories.length - 1).forEach(directory => {
if (path.length > 0) {
path += "/";
}
path += directory;
if (!fs.existsSync(`${cwd}/${path}`)) {
fs.mkdirSync(path);
}
});
let templateParams = {};
Object.assign(templateParams, {path, outputs});
Object.assign(templateParams, inputs);
if (fs.existsSync(`${cwd}/${output}`)) {
console.log(` Destination file already exists, skiping...`);
continue;
}
consolidate[lazySettings.engine](`${templatePath}/${file}`, templateParams, (err, result) => {
if (err) throw err;
let outputFile = fs.openSync(`${cwd}/${output}`, 'w');
fs.writeSync(outputFile, result);
fs.closeSync(outputFile);
});
}