From cecaecac5dbf2664023558441fbcdbf1bc86f0cb Mon Sep 17 00:00:00 2001 From: Santiago Palladino Date: Mon, 22 Jul 2019 17:22:54 -0300 Subject: [PATCH] Validate init params Validates that name is not empty, and that version is semver compatible. Only on interactive command. Fixes #1142 --- packages/cli/src/commands/init.ts | 9 ++++++++- packages/cli/src/prompts/prompt.ts | 1 + packages/cli/src/prompts/validators.ts | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 packages/cli/src/prompts/validators.ts diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index e1e7aac46..3bba68ce7 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -1,8 +1,10 @@ import push from './push'; import init from '../scripts/init'; +import semver from 'semver'; import { promptIfNeeded, InquirerQuestions } from '../prompts/prompt'; import { FileSystem } from '@openzeppelin/upgrades'; import ProjectFile from '../models/files/ProjectFile'; +import { notEmpty } from '../prompts/validators'; const name = 'init'; const signature = `${name} [project-name] [version]`; @@ -26,7 +28,7 @@ async function action(projectName: string, version: string, options: any): Promi const args = { name: projectName, version }; const props = getCommandProps(); - const defaults = FileSystem.parseJsonIfExists('package.json') || {}; + const defaults = FileSystem.parseJsonIfExists('package.json') || { version: '1.0.0' }; const prompted = await promptIfNeeded({ args, defaults, props }, interactive); const dependencies = link ? link.split(',') : []; @@ -50,10 +52,15 @@ function getCommandProps(): InquirerQuestions { name: { message: 'Welcome to the OpenZeppelin SDK! Choose a name for your project', type: 'input', + validate: notEmpty }, version: { message: 'Initial project version', type: 'input', + validate: input => { + if (semver.parse(input)) return true; + return `Invalid semantic version: ${input}`; + } }, }; } diff --git a/packages/cli/src/prompts/prompt.ts b/packages/cli/src/prompts/prompt.ts index 9b23f1260..dfae3616f 100644 --- a/packages/cli/src/prompts/prompt.ts +++ b/packages/cli/src/prompts/prompt.ts @@ -30,6 +30,7 @@ interface InquirerQuestion { when?: (answers: { [key: string]: any }) => boolean; transformer?: (value: string, answers: { [key: string]: any }) => string; normalize?: (input?: any) => any; + validate?: (input?: any) => boolean | string; } interface InquirerAnswer { diff --git a/packages/cli/src/prompts/validators.ts b/packages/cli/src/prompts/validators.ts new file mode 100644 index 000000000..f93b7a6cf --- /dev/null +++ b/packages/cli/src/prompts/validators.ts @@ -0,0 +1,4 @@ +export function notEmpty(input) { + if (input && input.length > 0) return true; + return "Please enter a non-empty value"; +} \ No newline at end of file