-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·85 lines (72 loc) · 2.18 KB
/
cli.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
#!/usr/bin/env node
require('es6-promise').polyfill();
const path = require('path');
const fs = require('fs');
const fse = require('fs-extra');
const argv = require('yargs').argv;
const os = require('os');
const download = require('download-git-repo');
const ora = require('ora');
const home = require('user-home');
const rm = require('rimraf').sync;
const util = require('util');
const chalk = require('chalk');
const pkg = require('./package.json');
const inputs = argv._;
const tmp = path.join(home, `.${pkg.name}`);
function logInfo() {
const msg = util.format.apply(util.format, arguments);
console.log(chalk.white(` ${msg}`));
}
function logError(message) {
if (message instanceof Error) {
message = message.message.trim()
}
const msg = util.format.apply(util.format, arguments);
console.error(chalk.red(` ${msg}`));
process.exit(1);
}
function downloadRepo() {
return new Promise(function(resolve, reject) {
download(`${pkg.author}/${pkg.name}`, tmp, { clone: false }, function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
if (inputs.length === 0) {
logInfo(`${pkg.name} v${pkg.version}`);
process.exit(0);
} else if (inputs.length > 1) {
logError('Invalid arguments');
}
let packageInfo = {};
packageInfo.name = inputs[0];
packageInfo.author = os.userInfo().username;
const spinner = ora('Downloading template')
spinner.start();
if (fs.exists(tmp)) {
rm(tmp);
}
downloadRepo().then(function() {
spinner.stop();
logInfo('Download template successfully.\n');
fse.copySync(path.join(tmp, 'template'), `./${packageInfo.name}`);
let packageFile = `./${packageInfo.name}/package.json`;
let packageFileText = fs.readFileSync(packageFile, 'utf8');
let packageFileObject = JSON.parse(packageFileText);
packageFileObject.name = packageInfo.name;
packageFileObject.author = packageInfo.author;
packageFileText = JSON.stringify(packageFileObject, null, 2);
logInfo(`Generated "${packageInfo.name}".\n`);
logInfo('To get started:\n');
logInfo(` cd ${packageInfo.name}`);
logInfo(' yarn');
logInfo(' npm start');
}).catch(function(err) {
logInfo('\n Error occurred:');
logError(err);
});