Skip to content

Commit

Permalink
feat: add 'singleValue' flag option to assign only one value per mult…
Browse files Browse the repository at this point in the history
…iple flag
  • Loading branch information
Roy Razon committed Nov 21, 2023
1 parent b3d8731 commit aef9c3c
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/interfaces/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ export type OptionFlagProps = FlagProps & {
helpValue?: string
options?: readonly string[]
multiple?: boolean
singleValue?: boolean
/**
* Delimiter to separate the values for a multiple value flag.
* Only respected if multiple is set to true. Default behavior is to
Expand Down
2 changes: 1 addition & 1 deletion src/parser/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export class Parser<
}
}

if (parsingFlags && this.currentFlag && this.currentFlag.multiple) {
if (parsingFlags && this.currentFlag && this.currentFlag.multiple && !this.currentFlag.singleValue) {
this.raw.push({flag: this.currentFlag.name, input, type: 'flag'})
continue
}
Expand Down
42 changes: 42 additions & 0 deletions test/parser/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, singleValue: 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, singleValue: 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, singleValue: 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'], {
Expand Down

0 comments on commit aef9c3c

Please sign in to comment.