-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·99 lines (83 loc) · 2.48 KB
/
cli.js
File metadata and controls
executable file
·99 lines (83 loc) · 2.48 KB
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
#!/usr/bin/env node
"use strict";
const meow = require("meow");
const fs = require("fs");
const validateProjectName = require("validate-npm-package-name");
const chalk = require("chalk");
const path = require("path");
const DIR = process.cwd();
const cli = meow(`
Usage
$ create-react-component <project-name>
Examples
$ create-react-component slider
`);
let appName;
function install(dir, name) {
if (!name) {
console.error(`${chalk.red("appName cant be null")}`);
process.exit(1);
}
appName = name;
const validationResult = validateProjectName(appName);
if (!validationResult.validForNewPackages) {
console.error(
`Could not create a project called ${chalk.red(
`"${appName}"`
)} because of npm naming restrictions:`
);
printValidationResults(validationResult.errors);
printValidationResults(validationResult.warnings);
process.exit(1);
}
const packagesPath = path.resolve(__dirname, "packages");
const newProjectPath = appName;
try {
fs.mkdirSync(`${dir}/${appName}`);
createDirectoryContents(packagesPath, newProjectPath);
console.log(
`Create successfully, your projectName: ${chalk.green(`"${appName}"`)}
use cd ${chalk.green(
`"${appName}"`
)} and npm install or (yarn) to enjoy it `
);
} catch (e) {
console.log(e);
process.exit(1);
}
}
function createDirectoryContents(templatePath, newProjectPath) {
const files = fs.readdirSync(templatePath);
files.forEach(file => {
const origFilePath = `${templatePath}/${file}`;
// get stats about the current file
const stats = fs.statSync(origFilePath);
if (stats.isFile()) {
let contents = fs.readFileSync(origFilePath, "utf8");
// update package name
if (file === "package.json") {
contents = contents.replace("create-react-component", appName);
}
if (file === ".npmtemplate") {
file = ".npmignore";
}
const writePath = `${DIR}/${newProjectPath}/${file}`;
fs.writeFileSync(writePath, contents, "utf8");
} else if (stats.isDirectory()) {
fs.mkdirSync(`${DIR}/${newProjectPath}/${file}`);
// recursive call
createDirectoryContents(
`${templatePath}/${file}`,
`${newProjectPath}/${file}`
);
}
});
}
function printValidationResults(results) {
if (typeof results !== "undefined") {
results.forEach(error => {
console.error(chalk.red(` * ${error}`));
});
}
}
install(DIR, cli.input[0]);