-
Notifications
You must be signed in to change notification settings - Fork 1k
/
create-redwood-app.js
502 lines (474 loc) · 14.8 KB
/
create-redwood-app.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
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
#!/usr/bin/env node
// This downloads the latest release of Redwood from https://github.com/redwoodjs/create-redwood-app/
// and extracts it into the supplied directory.
//
// Usage:
// `$ yarn create redwood-app ./path/to/new-project`
import { spawn } from 'child_process'
import path from 'path'
import chalk from 'chalk'
import checkNodeVersion from 'check-node-version'
import { prompt } from 'enquirer'
import execa from 'execa'
import fs from 'fs-extra'
import { Listr, figures } from 'listr2'
import terminalLink from 'terminal-link'
import { hideBin } from 'yargs/helpers'
import yargs from 'yargs/yargs'
import { name, version } from '../package'
/**
* To keep a consistent color/style palette between cli packages, such as
* @redwood/create-redwood-app and @redwood/cli, please keep them compatible
* with one and another. We'll might split up and refactor these into a
* separate package when there is a strong motivation behind it.
*
* Current files:
*
* - packages/cli/src/lib/colors.js
* - packages/create-redwood-app/src/create-redwood-app.js (this file)
*
*/
;(async () => {
// Styles for terminal
const style = {
error: chalk.bold.red,
warning: chalk.keyword('orange'),
success: chalk.greenBright,
info: chalk.grey,
header: chalk.bold.underline.hex('#e8e8e8'),
cmd: chalk.hex('#808080'),
redwood: chalk.hex('#ff845e'),
love: chalk.redBright,
green: chalk.green,
}
// Initial welcome message
console.log(
`${style.redwood(
'------------------------------------------------------------------'
)}`
)
console.log(`🌲⚡️ ${style.header('Welcome to RedwoodJS!')} ⚡️🌲`)
console.log(
`${style.redwood(
'------------------------------------------------------------------'
)}`
)
// Extract the args as provided by the user in the command line
const {
_: args,
'yarn-install': yarnInstall,
typescript,
overwrite,
telemetry: telemetry,
yarn1,
'git-init': gitInit,
} = yargs(hideBin(process.argv))
.scriptName(name)
.usage('Usage: $0 <project directory> [option]')
.example('$0 newapp')
.option('yarn-install', {
default: true,
type: 'boolean',
describe:
'Skip yarn install with --no-yarn-install. Also skips version requirements check.',
})
.option('typescript', {
alias: 'ts',
default: null,
type: 'boolean',
describe: 'Generate a TypeScript project.',
})
.option('overwrite', {
default: false,
type: 'boolean',
describe: "Create even if target directory isn't empty",
})
.option('telemetry', {
default: true,
type: 'boolean',
describe:
'Enables sending telemetry events for this create command and all Redwood CLI commands https://telemetry.redwoodjs.com',
})
.option('yarn1', {
default: false,
type: 'boolean',
describe: 'Use yarn 1. yarn 3 by default',
})
.option('git-init', {
alias: 'git',
default: null,
type: 'boolean',
describe: 'Initialize a git repository.',
})
.version(version)
.parse()
// Get the directory for installation from the args
const targetDir = String(args).replace(/,/g, '-')
// Throw an error if there is no target directory specified
if (!targetDir) {
console.error('Please specify the project directory')
console.log(
` ${chalk.cyan('yarn create redwood-app')} ${chalk.green(
'<project-directory>'
)}`
)
console.log()
console.log('For example:')
console.log(
` ${chalk.cyan('yarn create redwood-app')} ${chalk.green(
'my-redwood-app'
)}`
)
process.exit(1)
}
const newAppDir = path.resolve(process.cwd(), targetDir)
const appDirExists = fs.existsSync(newAppDir)
const templateDir = path.resolve(__dirname, '../template')
const createProjectTasks = ({ newAppDir, overwrite }) => {
return [
{
title: `${
appDirExists ? 'Using' : 'Creating'
} directory '${newAppDir}'`,
task: () => {
if (appDirExists && !overwrite) {
// make sure that the target directory is empty
if (fs.readdirSync(newAppDir).length > 0) {
console.error(
style.error(
`\n'${newAppDir}' already exists and is not empty\n`
)
)
process.exit(1)
}
} else {
fs.ensureDirSync(path.dirname(newAppDir))
}
fs.copySync(templateDir, newAppDir, { overwrite: overwrite })
// .gitignore is renamed here to force file inclusion during publishing
fs.rename(
path.join(newAppDir, 'gitignore.template'),
path.join(newAppDir, '.gitignore')
)
},
},
{
title: 'Converting to yarn 1',
enabled: () => yarn1,
task: () => {
// rm files:
// - .yarnrc.yml
// - .yarn
fs.rmSync(path.join(newAppDir, '.yarnrc.yml'))
fs.rmSync(path.join(newAppDir, '.yarn'), {
recursive: true,
force: true,
})
// rm after `.pnp.*`
const gitignore = fs.readFileSync(
path.join(newAppDir, '.gitignore'),
{
encoding: 'utf-8',
}
)
const [yarn1Gitignore, _yarn3Gitignore] = gitignore.split('.pnp.*')
fs.writeFileSync(path.join(newAppDir, '.gitignore'), yarn1Gitignore)
// rm `packageManager` from package.json
const packageJSON = fs.readJSONSync(
path.join(newAppDir, 'package.json')
)
delete packageJSON.packageManager
fs.writeJSONSync(path.join(newAppDir, 'package.json'), packageJSON, {
spaces: 2,
})
},
},
]
}
const installNodeModulesTasks = ({ newAppDir }) => {
return [
{
title: "Running 'yarn install'... (This could take a while)",
skip: () => {
if (yarnInstall === false) {
return 'skipped on request'
}
},
task: () => {
return execa('yarn install', {
shell: true,
cwd: newAppDir,
})
},
},
]
}
const sendTelemetry = ({ error } = {}) => {
// send 'create' telemetry event, or disable for new app
if (telemetry) {
const command = process.argv
// make command show 'create redwood-app [path] --flags'
command.splice(2, 0, 'create', 'redwood-app')
command[4] = '[path]'
let args = [
'--root',
newAppDir,
'--argv',
JSON.stringify(command),
'--duration',
Date.now() - startTime,
'--rwVersion',
version,
]
if (error) {
args = [...args, '--error', `"${error}"`]
}
spawn(process.execPath, [path.join(__dirname, 'telemetry.js'), ...args], {
detached: process.env.REDWOOD_VERBOSE_TELEMETRY ? false : true,
stdio: process.env.REDWOOD_VERBOSE_TELEMETRY ? 'inherit' : 'ignore',
}).unref()
} else {
fs.appendFileSync(
path.join(newAppDir, '.env'),
'REDWOOD_DISABLE_TELEMETRY=1\n'
)
}
}
const startTime = Date.now()
// Engine check Listr. Separate Listr to avoid https://github.com/cenk1cenk2/listr2/issues/296
// Boolean flag
let hasPassedEngineCheck = null
// Array of strings
let engineErrorLog = []
// Docs link for engine errors
const engineErrorDocsLink = terminalLink(
'Tutorial - Prerequisites',
'https://redwoodjs.com/docs/tutorial/chapter1/prerequisites'
)
await new Listr(
[
{
title: 'Checking node and yarn compatibility',
skip: () => {
if (yarnInstall === false) {
return 'Warning: skipping check on request'
}
},
task: () => {
return new Promise((resolve) => {
const { engines } = require(path.join(templateDir, 'package.json'))
// this checks all engine requirements, including Node.js and Yarn
checkNodeVersion(engines, (_error, result) => {
if (result.isSatisfied) {
hasPassedEngineCheck = true
return resolve()
}
const logStatements = Object.keys(result.versions)
.filter((name) => !result.versions[name].isSatisfied)
.map((name) => {
const { version, wanted } = result.versions[name]
return `${name} ${wanted} required, but you have ${version}`
})
engineErrorLog = logStatements
hasPassedEngineCheck = false
return resolve()
})
})
},
},
],
{ rendererOptions: { clearOutput: true } }
).run()
// Show a success message if required engines are present
if (hasPassedEngineCheck === true) {
console.log(`${style.success(figures.tick)} Compatibility checks passed`)
}
// Show an error and prompt if failed engines check
if (hasPassedEngineCheck === false) {
console.log(`${style.error(figures.cross)} Compatibility checks failed`)
console.log(
[
` ${style.warning(figures.warning)} ${engineErrorLog.join('\n')}`,
'',
` This may make your project incompatible with some deploy targets.`,
` See: ${engineErrorDocsLink}`,
'',
].join('\n')
)
// Prompt user for how to proceed
const response = await prompt({
type: 'select',
name: 'override-engine-error',
message: 'How would you like to proceed?',
choices: ['Override error and continue install', 'Quit install'],
initial: 0,
onCancel: () => process.exit(1),
})
// Quit the install if user selects this option, otherwise it will proceed
if (response['override-engine-error'] === 'Quit install') {
process.exit(1)
}
}
// Main install Listr
new Listr(
[
{
title: 'Language preference',
skip: () => typescript !== null,
task: async (ctx, task) => {
ctx.language = await task.prompt({
type: 'Select',
choices: ['TypeScript', 'JavaScript'],
message: 'Select your preferred coding language',
initial: 'TypeScript',
})
task.output = ctx.language
// Error code and exit if someone has disabled yarn install but selected JavaScript
if (!yarnInstall && ctx.language === 'JavaScript') {
throw new Error(
'JavaScript transpilation requires running yarn install. Please rerun create-redwood-app without disabling yarn install.'
)
}
},
options: {
persistentOutput: true,
},
},
{
title: 'Git preference',
skip: () => gitInit !== null,
task: async (ctx, task) => {
ctx.gitInit = await task.prompt({
type: 'Toggle',
message: 'Do you want to initialize a git repo?',
enabled: 'Yes',
disabled: 'no',
initial: 'Yes',
})
task.output = ctx.gitInit ? 'Initialize a git repo' : 'Skip'
},
options: {
persistentOutput: true,
},
},
{
title: 'Creating Redwood app',
task: () => new Listr(createProjectTasks({ newAppDir, overwrite })),
},
{
title: 'Installing packages',
task: () => new Listr(installNodeModulesTasks({ newAppDir })),
},
{
title: 'Convert TypeScript files to JavaScript',
// Enabled if user selects no to typescript prompt
// Enabled if user specified --no-ts via command line
enabled: (ctx) =>
yarnInstall === true &&
(typescript === false || ctx.language === 'JavaScript'),
task: () => {
return execa('yarn rw ts-to-js', {
shell: true,
cwd: newAppDir,
})
},
},
{
title: 'Generating types',
skip: () => yarnInstall === false,
task: () => {
return execa('yarn rw-gen', {
shell: true,
cwd: newAppDir,
})
},
},
{
title: 'Initializing a git repo',
enabled: (ctx) => gitInit || ctx.gitInit,
task: () => {
return execa(
'git init && git add . && git commit -m "Initial commit"',
{
shell: true,
cwd: newAppDir,
}
)
},
},
],
{
rendererOptions: { collapse: false },
exitOnError: true,
}
)
.run()
.then(() => {
sendTelemetry()
// zOMG the semicolon below is a real Prettier thing. What??
// https://prettier.io/docs/en/rationale.html#semicolons
;[
'',
style.success('Thanks for trying out Redwood!'),
'',
` ⚡️ ${style.redwood(
'Get up and running fast with this Quick Start guide'
)}: https://redwoodjs.com/docs/quick-start`,
'',
style.header('Join the Community'),
'',
`${style.redwood(
' ❖ Join our Forums'
)}: https://community.redwoodjs.com`,
`${style.redwood(' ❖ Join our Chat')}: https://discord.gg/redwoodjs`,
'',
style.header('Get some help'),
'',
`${style.redwood(
' ❖ Get started with the Tutorial'
)}: https://redwoodjs.com/docs/tutorial`,
`${style.redwood(
' ❖ Read the Documentation'
)}: https://redwoodjs.com/docs`,
'',
style.header('Stay updated'),
'',
`${style.redwood(
' ❖ Sign up for our Newsletter'
)}: https://www.redwoodjs.com/newsletter`,
`${style.redwood(
' ❖ Follow us on Twitter'
)}: https://twitter.com/redwoodjs`,
'',
`${style.header(`Become a Contributor`)} ${style.love('❤')}`,
'',
`${style.redwood(
' ❖ Learn how to get started'
)}: https://redwoodjs.com/docs/contributing`,
`${style.redwood(
' ❖ Find a Good First Issue'
)}: https://redwoodjs.com/good-first-issue`,
'',
`${style.header(`Fire it up!`)} 🚀`,
'',
`${style.redwood(` > ${style.green(`cd ${targetDir}`)}`)}`,
`${style.redwood(` > ${style.green(`yarn rw dev`)}`)}`,
'',
].map((item) => console.log(item))
})
.catch((e) => {
console.log()
console.log(e)
sendTelemetry({ error: e.message })
if (fs.existsSync(newAppDir)) {
console.log(
style.warning(`\nWarning: Directory `) +
style.cmd(`'${newAppDir}' `) +
style.warning(
`was created. However, the installation could not complete due to an error.\n`
)
)
}
process.exit(1)
})
})()