/
index.js
111 lines (99 loc) · 2.7 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const minimist = require('minimist');
const prompts = require('prompts');
const path = require('path');
const fs = require('fs');
const {
canSafelyOverwrite,
isValidPackageName,
toValidPackageName,
emptyDir,
} = require('./utils/helpers');
const { templateChoices } = require('./utils/templateOptions');
const defaultProjectName = 'ou-app';
const init = async () => {
console.log('init');
const cwd = process.cwd();
const argv = minimist(process.argv.slice(2), { boolean: true });
let targetDir;
let result = {};
try {
// Prompts:
// - Project name:
// - Package name:
// - Should create new directory:
// - Choose a template:
result = await prompts([
{
name: 'projectName',
type: 'text',
message: 'Project name:',
initial: defaultProjectName,
onState: (state) =>
(targetDir = String(state.value).trim() || defaultProjectName),
},
{
name: 'packageName',
type: () => (isValidPackageName(targetDir) ? null : 'text'),
message: 'Package name:',
initial: () => toValidPackageName(targetDir),
validate: (dir) =>
isValidPackageName(dir) || 'Invalid package.json name',
},
{
name: 'shouldCreateNewDir',
type: 'toggle',
message: 'Should create new directory:',
initial: false,
active: 'Yes',
inactive: 'No',
},
{
name: 'shouldOverwrite',
type: (shouldCreateNewDir) =>
!shouldCreateNewDir || canSafelyOverwrite(targetDir)
? null
: 'confirm',
message: () => {
const dirForPrompt =
targetDir === '.'
? 'Current directory'
: `Target directory "${targetDir}"`;
return `${dirForPrompt} is not empty. Remove existing files and continue?`;
},
},
{
name: 'template',
type: 'select',
choices: templateChoices,
message: 'Choose a template:',
},
]);
} catch (cancelled) {
console.log(cancelled.message);
process.exit(1);
}
const {
projectName,
packageName,
shouldCreateNewDir,
shouldOverwrite = false,
template,
} = result;
const root = shouldCreateNewDir ? path.join(cwd, projectName) : cwd;
if (shouldCreateNewDir) {
if (fs.existsSync(root) && shouldOverwrite) {
emptyDir(root);
} else if (!fs.existsSync(root)) {
fs.mkdirSync(root);
}
}
console.log(`\nScaffolding project in ${root}...`);
const pkg = { name: packageName, version: '0.0.0' };
fs.writeFileSync(
path.resolve(root, 'package.json'),
JSON.stringify(pkg, null, 2)
);
};
init().catch((e) => {
console.error(e);
});