Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creation messaging #1906

Merged
merged 2 commits into from
Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### New features

- [#1906: Improved messaging when creating a prototype](https://github.com/alphagov/govuk-prototype-kit/pull/1906)

### Fixes

- [#1887: You no longer need to press ctrl-c to exit if you say no to a new port](https://github.com/alphagov/govuk-prototype-kit/pull/1887)
Expand Down
76 changes: 68 additions & 8 deletions bin/cli
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,19 @@ const kitRoot = path.join(__dirname, '..')
const kitVersion = require('../package.json').version

const argv = parse(process.argv, {
booleans: ['no-version-control']
booleans: ['no-version-control', 'verbose', 'running-within-create-script']
})

const verboseLogger = !argv.options.verbose
? () => {}
: function () {
console.log('[verbose]', ...arguments)
}

const progressLogger = function () {
console.log(' - ', ...arguments)
}

const npmrc = `
audit=false
`.trimStart()
Expand Down Expand Up @@ -52,13 +62,33 @@ async function updatePackageJson (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 () {
if (argv.options['no-version-control']) {
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
}

Expand Down Expand Up @@ -143,6 +173,23 @@ function warnIfNpmStart (argv, env) {
}
}

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
}

function initialiserRequiresOldInitSyntax () {
const dependencies = require(path.join(getInstallLocation(), 'package.json')).dependencies || {}
const kitVersionParts = (dependencies['govuk-prototype-kit'] || '').split('.')

const requiresOldInitSyntax = kitVersionParts[0].endsWith('13') && Number(kitVersionParts[1]) <= 2
return requiresOldInitSyntax
}

async function runCreate () {
// Install as a two-stage bootstrap process.
//
Expand All @@ -157,6 +204,7 @@ async function runCreate () {
// as possible into stage two; stage one should ideally be able to install
// any future version of the kit.

console.log('')
const installDirectory = getInstallLocation()
const kitDependency = getChosenKitDependency()

Expand All @@ -167,25 +215,34 @@ async function runCreate () {
return
}

await fs.writeJson(path.join(installDirectory, 'package.json'), {}, packageJsonFormat)

console.log('Creating your prototype')

await writeEmptyPackageJson(installDirectory)

progressLogger('Installing dependencies')

await npmInstall(installDirectory, [kitDependency, 'govuk-frontend'])

const additionalArgs = Object.keys(argv.options).map(name => `--${name}="${argv.options[name]}"`)
let runningWithinCreateScriptFlag = '--running-within-create-script'

if (initialiserRequiresOldInitSyntax()) {
runningWithinCreateScriptFlag = '--'
}

progressLogger('Setting up your prototype')

await spawn('npx', ['govuk-prototype-kit', 'init', '--', installDirectory, ...additionalArgs], {
await spawn('npx', ['govuk-prototype-kit', 'init', runningWithinCreateScriptFlag, installDirectory, `--created-from-version=${kitVersion}`, ...(getArgumentsToPassThrough())], {
cwd: installDirectory,
stdio: 'inherit'
})
.then(displaySuccessMessage)
}

async function runInit () {
// `init` is stage two of the install process (see above), it should be
// called by `create` with the correct arguments.

if (process.argv[3] !== '--') {
if (!argv.options['running-within-create-script'] && process.argv[3] !== '--') {
usage()
process.exitCode = 2
return
Expand All @@ -201,7 +258,8 @@ async function runInit () {
fs.writeFile(path.join(installDirectory, '.npmrc'), npmrc, 'utf8'),
copyFile('LICENCE.txt'),
updatePackageJson(path.join(installDirectory, 'package.json'))
]).then(initialiseGitRepo)
])
.then(initialiseGitRepo)
}

async function runMigrate () {
Expand Down Expand Up @@ -271,6 +329,8 @@ function runServe () {
}

;(async () => {
verboseLogger(`Using kit version [${kitVersion}] for command [${argv.command}]`)
verboseLogger('Argv:', argv)
switch (argv.command) {
case 'create':
return runCreate()
Expand Down
3 changes: 3 additions & 0 deletions bin/utils/argv-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ function parse (argvInput, config = {}) {
}

args.forEach(arg => {
if (arg === '--') {
return
}
if (arg.startsWith('-')) {
const processedArgName = processOptionName(arg)
if (booleanOptions.includes(processedArgName)) {
Expand Down
5 changes: 1 addition & 4 deletions bin/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,10 @@ async function npmInstall (cwd, dependencies) {
return spawn(
'npm', [
'install',
'--no-audit',
'--loglevel=error',
'--omit=dev',
...dependencies
], {
cwd,
stdio: 'inherit'
stderr: 'inherit'
})
}

Expand Down
9 changes: 7 additions & 2 deletions migrator/file-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@ const fse = require('fs-extra')
// local dependencies
const { packageDir, projectDir } = require('../lib/utils/paths')
const { log, sanitisePaths } = require('./logger')
const { parse } = require('../bin/utils/argv-parser')

const argv = parse(process.argv, {
booleans: ['no-version-control', 'verbose']
})

async function verboseLog () {
await log(...arguments)
if (process.env.GPK_UPGRADE_DEBUG !== 'true') {
if (process.env.GPK_UPGRADE_DEBUG !== 'true' || argv.options.verbose) {
return
}
console.log(...arguments)
console.log('[debug]', ...arguments)
}

async function verboseLogError (e) {
Expand Down