From c8a511e6cf4cf04b92a67b803ce10e3703128eea Mon Sep 17 00:00:00 2001 From: Justin Edelson Date: Mon, 1 Mar 2021 09:30:26 -0500 Subject: [PATCH] feat(args): Support checking options after parse function fixes #162 --- .circleci/config.yml | 1 + src/args.ts | 2 ++ src/errors.ts | 7 +++++++ src/parse.ts | 6 +++++- test/parse.test.ts | 17 +++++++++++++++++ 5 files changed, 32 insertions(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index e84ccf4..ae76d71 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -7,6 +7,7 @@ jobs: working_directory: ~/cli environment: NYC: "yarn exec nyc -- --nycrc-path node_modules/@oclif/nyc-config/.nycrc" + FORCE_COLOR: "0" steps: - checkout - restore_cache: &restore_cache diff --git a/src/args.ts b/src/args.ts index f992da5..a4c0d6e 100644 --- a/src/args.ts +++ b/src/args.ts @@ -9,6 +9,7 @@ export interface IArg { parse?: ParseFn; default?: T | (() => T); options?: string[]; + postParseOptions?: string[]; } export interface ArgBase { @@ -19,6 +20,7 @@ export interface ArgBase { default?: T | (() => T); input?: string; options?: string[]; + postParseOptions?: string[]; } export type RequiredArg = ArgBase & { diff --git a/src/errors.ts b/src/errors.ts index dfaf1f5..4325546 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -98,3 +98,10 @@ export class ArgInvalidOptionError extends CLIParseError { super({parse: {}, message}) } } + +export class ArgInvalidPostParseOptionError extends CLIParseError { + constructor(arg: Arg, input: string) { + const message = `Expected ${input} to be one of: ${arg.postParseOptions!.join(', ')} after parsing` + super({parse: {}, message}) + } +} diff --git a/src/parse.ts b/src/parse.ts index ff85dd1..aeb8081 100644 --- a/src/parse.ts +++ b/src/parse.ts @@ -229,7 +229,11 @@ export class Parser { + it('accepts valid postParseOptions', () => { + const out = parse(['myotheropt'], { + args: [{name: 'foo', parse: s => s.toUpperCase(), postParseOptions: ['MYOPT', 'MYOTHEROPT']}], + }) + expect(out.args.foo).to.equal('MYOTHEROPT') + }) + + it('fails when invalid', () => { + expect(() => { + parse(['invalidopt'], { + args: [{name: 'foo', parse: s => s.toUpperCase(), postParseOptions: ['MYOPT', 'MYOTHEROPT']}], + }) + }).to.throw('Expected INVALIDOPT to be one of: MYOPT, MYOTHEROPT after parsing') + }) + }) + describe('env', () => { it('accepts as environment variable', () => { process.env.TEST_FOO = '101'