From 629d482d0059486c78054a66983a3a228ece7993 Mon Sep 17 00:00:00 2001 From: Mike Donnalley Date: Fri, 1 Mar 2024 13:17:40 -0700 Subject: [PATCH] fix: allow arg to be empty string --- src/parser/parse.ts | 2 +- src/parser/validate.ts | 3 ++- test/parser/validate.test.ts | 25 +++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/parser/parse.ts b/src/parser/parse.ts index 2cf51b511..eefd9ea1c 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -305,7 +305,7 @@ export class Parser< } for (const token of tokens) { - if (args[token.arg]) continue + if (args[token.arg] !== undefined) continue argv.push(token.input) } diff --git a/src/parser/validate.ts b/src/parser/validate.ts index d2caee751..9e2b32c21 100644 --- a/src/parser/validate.ts +++ b/src/parser/validate.ts @@ -44,7 +44,8 @@ export async function validate(parse: {input: ParserInput; output: ParserOutput} }) } - if (arg.required && !parse.output.args[name] && parse.output.args[name] !== 0) { + // Only add if it's required and undefined. Allow falsy values like empty strings and 0. + if (arg.required && parse.output.args[name] === undefined) { missingRequiredArgs.push(arg) } } diff --git a/test/parser/validate.test.ts b/test/parser/validate.test.ts index ac9ee6d20..b85fa1b9c 100644 --- a/test/parser/validate.test.ts +++ b/test/parser/validate.test.ts @@ -121,6 +121,31 @@ describe('validate', () => { await validate({input, output}) }) + it('allows empty string as arg', async () => { + const input = { + argv: [], + flags: {}, + args: { + emptyString: {required: true}, + }, + strict: true, + context: {}, + '--': true, + } + + const output = { + args: {emptyString: ''}, + argv: [''], + raw: [], + metadata: { + flags: {}, + }, + } + + // @ts-expect-error + await validate({input, output}) + }) + it('throws when required flag is undefined', async () => { const input = { argv: [],