-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (60 loc) · 2.29 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
const fs = require('fs');
const path = require('path');
const promisify = require('util.promisify');
const clc = require('cli-color');
const prettier = require('prettier');
const extend = require('extend');
const capitalize = require('capitalize');
const mkdirp = require('mkdirp');
const writeFile = promisify(fs.writeFile);
const stat = promisify(fs.stat);
const mkdir = promisify(mkdirp);
function pretting(code, parser = 'babylon') {
return prettier.format(code, {
tabWidth: 4,
bracketSpacing: false,
singleQuote: true,
jsxBracketSameLine: true,
parser: parser
});
}
function generate(componentNames, customConfig = {}, allowOverride = false) {
if (!componentNames || componentNames.length === 0) {
const error = new Error('Error: Provide a component name');
console.error(clc.red(error));
return Promise.reject(error);
}
const config = extend(true, {}, require('./config'), customConfig);
const {output, filenames, templates} = config;
return Promise.all(componentNames.map((name) => {
name = capitalize(name);
const filepath = path.join(path.resolve(output), name);
return new Promise((resolve, reject) => {
allowOverride ? resolve() : stat(filepath)
.then(() => reject(new Error(`Error: Exists file path, ${filepath}`)))
.catch(() => resolve());
}).then(() => {
return Promise.all(Object.keys(filenames).map((key) => {
const filename = filenames[key].replace('[name]', name);
const fullpath = path.join(filepath, filename);
return mkdir(filepath).then(() => {
const source = pretting(
templates[key](name),
key === 'style' ? 'postcss' : 'babylon'
);
return writeFile(fullpath, source, 'utf8');
}).then(() => {
console.info(clc.greenBright(`Info: Created ${path.join(output, name, filename)}`));
});
}));
}).catch((err) => {
console.error(clc.red(err.message));
});
})).then(() => {
console.info(clc.cyan('Info: Completed!'));
});
}
module.exports = {
generate,
pretting
};