diff --git a/src/interfaces/parser.ts b/src/interfaces/parser.ts index 252f3dc9c..d6899dfec 100644 --- a/src/interfaces/parser.ts +++ b/src/interfaces/parser.ts @@ -208,6 +208,12 @@ export type OptionFlagProps = FlagProps & { helpValue?: string options?: readonly string[] multiple?: boolean + /** + * Parse one value per flag; allow `-m val1 -m val2`, disallow `-m val1 val2`. + * Set to true to use "multiple: true" flags together with args. + * Only respected if multiple is set to true. + */ + multipleNonGreedy?: boolean /** * Delimiter to separate the values for a multiple value flag. * Only respected if multiple is set to true. Default behavior is to diff --git a/src/parser/parse.ts b/src/parser/parse.ts index 7c8fc49b5..3faf94262 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -200,7 +200,7 @@ export class Parser< } } - if (parsingFlags && this.currentFlag && this.currentFlag.multiple) { + if (parsingFlags && this.currentFlag && this.currentFlag.multiple && !this.currentFlag.multipleNonGreedy) { this.raw.push({flag: this.currentFlag.name, input, type: 'flag'}) continue } diff --git a/test/parser/parse.test.ts b/test/parser/parse.test.ts index bb19aace5..21edd0ad8 100644 --- a/test/parser/parse.test.ts +++ b/test/parser/parse.test.ts @@ -631,6 +631,48 @@ See more help with --help`) }) }) + describe('multiple flags with single value', () => { + it('parses multiple flags with single value', async () => { + const out = await parse(['--bar', 'a', 'b', '--bar=c', '--baz=d', 'e'], { + args: {argOne: Args.string()}, + flags: { + bar: Flags.string({multiple: true, multipleNonGreedy: true}), + baz: Flags.string({multiple: true}), + }, + }) + expect(out.flags.baz?.join('|')).to.equal('d|e') + expect(out.flags.bar?.join('|')).to.equal('a|c') + expect(out.args).to.deep.equal({argOne: 'b'}) + }) + + it('parses multiple flags with single value multiple args', async () => { + const out = await parse(['c', '--bar', 'a', 'b'], { + args: {argOne: Args.string(), argTwo: Args.string()}, + flags: { + bar: Flags.string({multiple: true, multipleNonGreedy: true}), + }, + }) + expect(out.flags.bar?.join('|')).to.equal('a') + expect(out.args).to.deep.equal({argOne: 'c', argTwo: 'b'}) + }) + + it('fails to parse with single value and no args option', async () => { + let message = '' + + try { + await parse(['--bar', 'a', 'b'], { + flags: { + bar: Flags.string({multiple: true, multipleNonGreedy: true}), + }, + }) + } catch (error: any) { + message = error.message + } + + expect(message).to.include('Unexpected argument: b') + }) + }) + describe('strict: false', () => { it('skips flag parsing after "--"', async () => { const out = await parse(['foo', 'bar', '--', '--myflag'], {