-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·83 lines (70 loc) · 2.05 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
#!/usr/bin/env node
const fs = require('fs');
const Mustache = require('mustache');
const changeCase = require('change-case');
const templates = require('./templates');
const program = require('commander');
program
.arguments('<name>')
.option('-s, --stateful', 'Stateful component')
.action(name => {
try {
return main(name, program.stateful);
} catch (e) {
console.log(e);
process.exit(1);
}
})
.parse(process.argv);
async function main(name, stateful) {
const { pascalCase, paramCase } = parseName(name);
await makeDirIfNotExist(paramCase);
const rendered = renderTemplates(templates, { pascalCase, paramCase });
saveFiles(paramCase, rendered, stateful);
}
async function saveFiles(componentName, renderedTemplates, stateful) {
await writeFile(`${componentName}/index.js`, renderedTemplates.index);
await writeFile(
`${componentName}/${componentName}.js`,
stateful ? renderedTemplates.statefulComponent : renderedTemplates.component
);
await writeFile(
`${componentName}/${componentName}.css`,
renderedTemplates.style
);
}
function renderTemplates(templates, { pascalCase, paramCase }) {
return renderTuple(templates).reduce(function reducer(obj, [key, val]) {
obj[key] = val;
return obj;
}, {});
function render(template) {
return Mustache.render(template, { pascalCase, paramCase });
}
function renderTuple(templates) {
return Object.keys(templates).map(k => [k, render(templates[k])]);
}
}
async function writeFile(filename, fileInput) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, fileInput, err => {
if (err) {
return reject(err);
}
return resolve();
});
});
}
function parseName(name) {
const paramCase = changeCase.param(name);
const pascalCase = changeCase.pascal(name);
return { paramCase, pascalCase };
}
function makeDirIfNotExist(dirname) {
return new Promise((resolve, reject) =>
fs.mkdir(
dirname,
error => (error && error.code !== 'EEXIST' ? reject(error) : resolve())
)
);
}