-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
207 lines (179 loc) · 5.66 KB
/
index.ts
File metadata and controls
207 lines (179 loc) · 5.66 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { execSync } from 'child_process'
import { basename, join, relative } from 'path'
import { extract } from 'tar'
import getRegistry from 'get-registry'
import parse from 'yargs-parser'
import prompts from 'prompts'
import axios from 'axios'
import which from 'which-pm-runs'
import kleur from 'kleur'
import * as fs from 'fs'
let project: string
let rootDir: string
const { version } = require('../package.json')
const cwd = process.cwd()
const argv = parse(process.argv.slice(2), {
alias: {
ref: ['r'],
forced: ['f'],
git: ['g'],
mirror: ['m'],
prod: ['p'],
template: ['t'],
yes: ['y'],
help: ['h'],
},
})
function supports(command: string) {
try {
execSync(command, { stdio: 'ignore' })
return true
} catch {
return false
}
}
async function getName() {
if (argv._[0]) return '' + argv._[0]
const { name } = await prompts({
type: 'text',
name: 'name',
message: 'Project name:',
initial: 'koishi-app',
})
return name.trim() as string
}
// baseline is Node 12 so can't use rmSync
function emptyDir(root: string) {
for (const file of fs.readdirSync(root)) {
const abs = join(root, file)
if (fs.lstatSync(abs).isDirectory()) {
emptyDir(abs)
fs.rmdirSync(abs)
} else {
fs.unlinkSync(abs)
}
}
}
async function confirm(message: string) {
const { yes } = await prompts({
type: 'confirm',
name: 'yes',
initial: 'Y',
message,
})
return yes as boolean
}
async function prepare() {
if (!fs.existsSync(rootDir)) {
return fs.mkdirSync(rootDir, { recursive: true })
}
const files = fs.readdirSync(rootDir)
if (!files.length) return
if (!argv.forced && !argv.yes) {
console.log(kleur.yellow(` Target directory "${project}" is not empty.`))
const yes = await confirm('Remove existing files and continue?')
if (!yes) process.exit(0)
}
emptyDir(rootDir)
}
async function scaffold() {
console.log(kleur.dim(' Scaffolding project in ') + project + kleur.dim(' ...'))
const mirror = argv.mirror === true ? 'https://registry.npmmirror.com' : argv.mirror
const registry = (mirror || await getRegistry() || 'https://registry.npmjs.org').replace(/\/$/, '')
console.log(kleur.dim(` Using registry: ${registry}\n`))
const template = argv.template || '@koishijs/boilerplate'
try {
const { data: remote } = await axios.get(`${registry}/${template}`)
const version = remote['dist-tags'][argv.ref || 'latest']
const url = remote.versions[version].dist.tarball
const { data } = await axios.get<NodeJS.ReadableStream>(url, { responseType: 'stream' })
await new Promise<void>((resolve, reject) => {
const stream = data.pipe(extract({ cwd: rootDir, newer: true, strip: 1 }))
stream.on('finish', resolve)
stream.on('error', reject)
})
} catch (err) {
if (!axios.isAxiosError(err) || !err.response) throw err
const { status, statusText } = err.response
console.log(`${kleur.red('error')} request failed with status code ${status} ${statusText}`)
process.exit(1)
}
writePackageJson()
writeEnvironment()
console.log(kleur.green(' Done.\n'))
}
function writePackageJson() {
const filename = join(rootDir, 'package.json')
const meta = require(filename)
meta.name = project
meta.private = true
meta.version = '0.0.0'
if (argv.prod) {
// https://github.com/koishijs/koishi/issues/994
// Do not use `NODE_ENV` or `--production` flag.
// Instead, simply remove `devDependencies` and `workspaces`.
delete meta.workspaces
delete meta.devDependencies
}
fs.writeFileSync(filename, JSON.stringify(meta, null, 2) + '\n')
}
function writeEnvironment() {
const filename = join(rootDir, '.env')
if (!fs.existsSync(filename)) return
const content = fs.readFileSync(filename, 'utf8')
fs.writeFileSync(filename, content)
}
async function initGit() {
if (!argv.git || !supports('git --version')) return
execSync('git init', { stdio: 'ignore', cwd: rootDir })
console.log(kleur.green(' Done.\n'))
}
async function install() {
// with `-y` option, we don't install dependencies
if (argv.yes) return
const agent = which()?.name || 'npm'
const yes = await confirm('Install and start it now?')
if (yes) {
execSync([agent, 'install'].join(' '), { stdio: 'inherit', cwd: rootDir })
execSync([agent, 'run', 'start'].join(' '), { stdio: 'inherit', cwd: rootDir })
} else {
console.log(kleur.dim(' You can start it later by:\n'))
if (rootDir !== cwd) {
const related = relative(cwd, rootDir)
console.log(kleur.blue(` cd ${kleur.bold(related)}`))
}
console.log(kleur.blue(` ${agent === 'yarn' ? 'yarn' : `${agent} install`}`))
console.log(kleur.blue(` ${agent === 'yarn' ? 'yarn start' : `${agent} run start`}`))
console.log()
}
}
async function start() {
if (argv.help) {
console.log(`
Usage: create-koishi [name] [options]
Options:
-t, --template <name> Template to use (default: @koishijs/boilerplate)
-r, --ref <ref> Reference to use (default: latest)
-f, --forced Force overwrite target directory
-g, --git Initialize git repository
-m, --mirror [url] Use specific registry mirror (like https://registry.npmmirror.com)
-p, --prod Production mode
-y, --yes Skip prompts
-h, --help Show this help message
`)
return
}
console.log()
console.log(` ${kleur.bold('Create Koishi')} ${kleur.blue(`v${version}`)}`)
console.log()
const name = await getName()
rootDir = join(cwd, name)
project = basename(rootDir)
await prepare()
await scaffold()
await initGit()
await install()
}
start().catch((e) => {
console.error(e)
})