/
cli
executable file
·403 lines (336 loc) · 11.8 KB
/
cli
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
#!/usr/bin/env node
const fs = require('fs-extra')
const path = require('path')
const { spawn, exec } = require('../lib/exec')
const { parse } = require('./utils/argv-parser')
const { prepareMigration, preflightChecks } = require('../migrator')
const { npmInstall, packageJsonFormat, getPackageVersionFromPackageJson, splitSemverVersion } = require('./utils')
const { recursiveDirectoryContentsSync } = require('../lib/utils')
const { appViewsDir } = require('../lib/utils/paths')
// Avoid requiring any kit server code at the top-level as we might want to
// change environment variables below.
const currentDirectory = process.cwd()
const kitRoot = path.join(__dirname, '..')
const kitVersion = require('../package.json').version
const kitProjectName = require('../package.json').name
const argv = parse(process.argv, {
booleans: ['no-version-control', 'verbose', 'running-within-create-script', 'use-njk-extensions']
})
const verboseLogger = !argv.options.verbose
? () => {}
: function () {
console.log('[verbose]', ...arguments)
}
const progressLogger = function () {
if (argv.command === 'init') {
const versionOfInstaller = argv.options['created-from-version']
if (!versionOfInstaller) {
return
}
const version = splitSemverVersion(versionOfInstaller)
if (version.major === 13 && version.minor < 2) {
return
}
}
console.log(' - ', ...arguments)
}
const npmrc = `
audit=false
`.trimStart()
const gitignore = `
# Node.js ignores
node_modules/
# Prototype ignores - per-user
.tmp/
.env
migrate.log
usage-data-config.json
# General ignores
.DS_Store
.idea
`.trimStart()
const packageJson = {
scripts: {
dev: 'govuk-prototype-kit dev',
serve: 'govuk-prototype-kit serve',
start: 'govuk-prototype-kit start'
}
}
async function updatePackageJson (packageJsonPath) {
let newPackageJson = Object.assign({}, packageJson)
newPackageJson = Object.assign(newPackageJson, await fs.readJson(packageJsonPath))
await fs.writeJson(packageJsonPath, newPackageJson, packageJsonFormat)
}
function displaySuccessMessage () {
console.log('')
console.log('Prototype created')
if (argv.paths.length > 0) {
console.log('')
console.log('Change to your prototype directory:')
console.log(` cd ${argv.paths[0]}`)
}
console.log('')
console.log('To run your prototype:')
console.log(' npm run dev')
console.log('')
}
async function initialiseGitRepo () {
const noVersionControlArg = 'no-version-control'
if (argv.options[noVersionControlArg]) {
verboseLogger(`User specified --${noVersionControlArg}, skipping.`)
return
}
progressLogger('Initialising git')
try {
await exec('git init --initial-branch=main && git add -A .', {})
} catch (e) {
verboseLogger('Failed to initialise git')
verboseLogger(e.message)
verboseLogger(e.errorOutput)
return
}
const failSilently = () => {}
const commitMessage = 'Create prototype'
await exec(`git commit -am "${commitMessage}"`)
.catch(() =>
exec(`git -c "user.email=gov.uk-prototype@digital.cabinet-office.gov.uk" -c "user.name=GOV.UK Prototype Kit" commit -am "${commitMessage}"`)
)
.catch(failSilently)
}
function usage () {
const prog = 'npx govuk-prototype-kit'
console.log(`
${prog} <command>
Usage:
${prog} create
${prog} create /exact/location/to/create/in
${prog} create relative/location/to/create/in
${prog} dev
${prog} serve
${prog} start
${prog} migrate`
)
}
function getInstallLocation () {
const chosenPath = argv.paths[0]
if (chosenPath) {
if (path.isAbsolute(chosenPath)) {
return chosenPath
}
return path.resolve(chosenPath)
}
return currentDirectory
}
function getChosenKitDependency () {
const defaultValue = 'govuk-prototype-kit'
const versionRequested = argv.options.version || argv.options.v
if (!versionRequested) {
return defaultValue
}
if (versionRequested === 'local' || versionRequested === 'local-symlink') {
return kitRoot
} else if (versionRequested) {
if (versionRequested.match(/\d+\.\d+\.\d+/) ||
versionRequested.match(/\d+\.\d+\.\d+-alpha\.\d+]/) ||
versionRequested.match(/\d+\.\d+\.\d+-beta\.\d+]/)
) {
return `${defaultValue}@${versionRequested}`
} else {
return versionRequested
}
}
return defaultValue
}
// do some heuristics to try and catch situations where a user has run
// `npm start` (the wrong command) locally and warn them.
function warnIfNpmStart (argv, env) {
if (
argv.command === 'start' && // if user ran serve script then assume they know what they want
env.NODE_ENV !== 'production' && // some hosting services set NODE_ENV
env.PORT === undefined && // some hosting services set PORT
env.PASSWORD === undefined // user should have set PASSWORD when setting up hosting
) {
console.warn('Warning: It looks like you may have run the command `npm start` locally.')
console.warn('try running `npm run dev`')
console.warn()
console.warn('If you see the above warning when trying to host your prototype online,')
console.warn('it may be that your hosting service needs further configuration.')
console.warn()
}
}
function writeEmptyPackageJson (installDirectory) {
return fs.writeJson(path.join(installDirectory, 'package.json'), {})
}
function getArgumentsToPassThrough () {
const additionalArgs = Object.keys(argv.options).map(name => `--${name}="${argv.options[name]}"`)
return additionalArgs
}
async function initialiserRequiresOldInitSyntax () {
const version = await getPackageVersionFromPackageJson(path.join(getInstallLocation(), 'node_modules', 'govuk-prototype-kit', 'package.json'))
const requiresOldInitSyntax = version.major === 13 && version.minor < 2
return requiresOldInitSyntax
}
async function runCreate () {
// Install as a two-stage bootstrap process.
//
// In stage one (`create`) we create an empty project folder and install
// govuk-prototype-kit and govuk-frontend, then bootstrap stage two from
// the newly installed package.
//
// In stage two (`init`) we do the actual setup of the starter files.
//
// Doing it this way means we can be sure the version of the cli matches
// the version of the kit the user ends up with. Try to put as much logic
// as possible into stage two; stage one should ideally be able to install
// any future version of the kit.
verboseLogger('Cli running from', __filename)
console.log('')
const installDirectory = getInstallLocation()
const kitDependency = getChosenKitDependency()
await fs.ensureDir(installDirectory)
if ((await fs.readdir(installDirectory)).length > 0) {
console.error(`Directory ${installDirectory} is not empty, please specify an empty location.`)
process.exitCode = 3
return
}
console.log('Creating your prototype')
await writeEmptyPackageJson(installDirectory)
progressLogger('Installing dependencies')
await npmInstall(installDirectory, [kitDependency, 'govuk-frontend', '@govuk-prototype-kit/common-templates'])
if ((argv.options.version || argv.options.v) === 'local-symlink') {
const dependencyInstallLocation = path.join(installDirectory, 'node_modules', kitProjectName)
await fs.remove(dependencyInstallLocation)
await fs.ensureSymlink(kitDependency, dependencyInstallLocation)
}
let runningWithinCreateScriptFlag = '--running-within-create-script'
if (await initialiserRequiresOldInitSyntax()) {
runningWithinCreateScriptFlag = '--'
}
progressLogger('Setting up your prototype')
await spawn('npx', ['govuk-prototype-kit', 'init', runningWithinCreateScriptFlag, installDirectory, `--created-from-version=${kitVersion}`, ...(getArgumentsToPassThrough())], {
cwd: installDirectory,
stdio: 'inherit'
})
.then(displaySuccessMessage)
}
async function createStarterFiles (installDirectory) {
await fs.copy(path.join(kitRoot, 'prototype-starter'), installDirectory)
async function addToConfigFile (key, value) {
const configFileLocation = path.join(installDirectory, 'app', 'config.json')
const config = await fs.readJson(configFileLocation)
config[key] = value
await fs.writeJson(configFileLocation, config, { spaces: 2 })
}
function renameAllHtmlFilesToNjk () {
return recursiveDirectoryContentsSync(appViewsDir)
.filter(filePath => filePath.endsWith('.html'))
.map(filePath => fs.move(
path.join(appViewsDir, filePath),
path.join(appViewsDir, filePath.substring(0, filePath.length - '.html'.length) + '.njk')
))
}
if (argv.options['use-njk-extensions']) {
await Promise.all([
addToConfigFile('useNjkExtensions', true),
...renameAllHtmlFilesToNjk()
])
}
}
async function runInit () {
// `init` is stage two of the install process (see above), it should be
// called by `create` with the correct arguments.
if (!argv.options['running-within-create-script'] && process.argv[3] !== '--') {
usage()
process.exitCode = 2
return
}
const installDirectory = getInstallLocation()
const copyFile = (fileName) => fs.copy(path.join(kitRoot, fileName), path.join(installDirectory, fileName))
await Promise.all([
createStarterFiles(installDirectory),
fs.writeFile(path.join(installDirectory, '.gitignore'), gitignore, 'utf8'),
fs.writeFile(path.join(installDirectory, '.npmrc'), npmrc, 'utf8'),
copyFile('LICENCE.txt'),
updatePackageJson(path.join(installDirectory, 'package.json'))
])
.then(initialiseGitRepo)
}
async function runMigrate () {
// migrate as a two-stage bootstrap process.
//
// In stage one we install govuk-prototype-kit, then bootstrap stage two
// from the newly installed package.
//
// In stage two (with the magic arguments) we do the actual migration with
// the starter files.
//
// Doing it this way means we can be sure the version of the cli matches
// the version of the kit the user ends up with. Try to put as much logic
// as possible into stage two; stage one should ideally be able to migrate
// to any future version of the kit.
if (process.argv[3] !== '--') {
// stage one
const kitDependency = getChosenKitDependency()
const projectDirectory = process.cwd()
const preflightChecksPassed = await preflightChecks()
if (!preflightChecksPassed) {
process.exitCode = 1
return
}
await prepareMigration(kitDependency, projectDirectory)
await spawn('npx', ['govuk-prototype-kit', 'migrate', '--', projectDirectory], {
stdio: 'inherit'
})
} else {
// stage two
if (process.argv.length !== 5) {
usage()
process.exitCode = 2
return
}
const projectDirectory = process.argv[4]
await Promise.all([
updatePackageJson(path.join(projectDirectory, 'package.json')),
fs.writeFile(path.join(projectDirectory, '.npmrc'), npmrc, 'utf8'),
fs.access(path.join(projectDirectory, '.gitignore'))
.catch(() => fs.writeFile(path.join(projectDirectory, '.gitignore'), gitignore, 'utf8'))
])
await require('../migrator').migrate()
}
}
async function runDev () {
console.log(`GOV.UK Prototype Kit ${kitVersion}`)
console.log('')
console.log('starting...')
await require('../lib/dev-server').runDevServer()
}
function runServe () {
warnIfNpmStart(argv, process.env)
process.env.NODE_ENV = process.env.NODE_ENV || 'production'
require('../lib/build.js').generateAssetsSync()
require('../listen-on-port')
}
;(async () => {
verboseLogger(`Using kit version [${kitVersion}] for command [${argv.command}]`)
verboseLogger('Argv:', argv)
switch (argv.command) {
case 'create':
return runCreate()
case 'init':
return runInit()
case 'dev':
return runDev()
case 'start':
return runServe()
case 'serve':
return runServe()
case 'migrate':
return runMigrate()
case 'version':
console.log(kitVersion)
break
default:
usage()
process.exitCode = 2
}
})()