Skip to content
This repository has been archived by the owner on Aug 22, 2023. It is now read-only.

feat: Add 'singleValue' flag option to assign only one value per multiple flag #79

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export type IOptionFlag<T> = IFlagBase<T, string> & {
helpValue?: string;
default?: Default<T | undefined>;
multiple: boolean;
singleValue: boolean;
input: string[];
options?: string[];
}
Expand Down Expand Up @@ -73,6 +74,7 @@ export function build<T>(defaults: Partial<IOptionFlag<T>>): Definition<T> {
...options,
input: [] as string[],
multiple: Boolean(options.multiple),
singleValue: Boolean(options.singleValue),
type: 'option',
} as any
}
Expand Down
2 changes: 1 addition & 1 deletion src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']
}
// not actually a flag if it reaches here so parse as an arg
}
if (parsingFlags && this.currentFlag && this.currentFlag.multiple) {
if (parsingFlags && this.currentFlag && this.currentFlag.multiple && !this.currentFlag.singleValue) {
this.raw.push({type: 'flag', flag: this.currentFlag.name, input})
continue
}
Expand Down
36 changes: 36 additions & 0 deletions test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,42 @@ See more help with --help`)
})
})

describe('multiple flags with single value', () => {
it('parses multiple flags with single value', () => {
const out = parse(['--bar', 'a', 'b', '--bar=c', '--baz=d', 'e'], {
args: [{name: 'argOne'}],
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', () => {
const out = parse(['c', '--bar', 'a', 'b'], {
args: [{name: 'argOne'}, {name: 'argTwo'}],
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', () => {
expect(() => {
parse(['--bar', 'a', 'b'], {
flags: {
bar: flags.string({multiple: true, singleValue: true}),
},
})
}).to.throw('Unexpected argument: b')
})
})

describe('strict: false', () => {
it('skips flag parsing after "--"', () => {
const out = parse(['foo', 'bar', '--', '--myflag'], {
Expand Down