Skip to content

Commit

Permalink
feat(breadc): support no- boolean option
Browse files Browse the repository at this point in the history
  • Loading branch information
yjl9903 committed Feb 25, 2023
1 parent 0ac2ffa commit c94b26b
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 5 deletions.
14 changes: 11 additions & 3 deletions packages/breadc/src/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@ export function makeOption<
const match = OptionRE.exec(format);
if (match) {
name = match[2];
if (name.startsWith('no-')) {
throw new BreadcError(`Can not parse option format (${format})`);
}

if (match[1]) {
short = match[1][1];
}

if (match[3]) {
if (name.startsWith('no-')) {
throw new BreadcError(`Can not parse option format (${format})`);
}

const initial = config.default ?? '';
return <Option<F, T>>{
format,
Expand All @@ -39,10 +40,17 @@ export function makeOption<
cast: config.cast
};
} else {
if (name.startsWith('no-')) {
name = name.slice(3);
// @ts-ignore
config.default = true;
}

const initial =
config.default === undefined || config.default === null
? false
: config.default;

return <Option<F, T>>{
format,
type: 'boolean',
Expand Down
6 changes: 4 additions & 2 deletions packages/breadc/test/breadc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,10 @@ describe('Breadc Error', () => {
).toThrowErrorMatchingInlineSnapshot(
'"Can not parse option format (--root <...files>)"'
);
expect(() => cli.option('--no-root')).toThrowErrorMatchingInlineSnapshot(
'"Can not parse option format (--no-root)"'
expect(() =>
cli.option('--no-root <root>')
).toThrowErrorMatchingInlineSnapshot(
'"Can not parse option format (--no-root <root>)"'
);
});
});
Expand Down
1 change: 1 addition & 0 deletions packages/breadc/test/command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ describe('Help command', () => {
const cli = breadc('cli');
cli.option('--host <addr>', { description: 'Host address' });
cli.option('-r, --remote', { description: 'Enable remote' });
cli.option('--no-open', { description: 'Open page' });

expect(await cli.run(['-h'])).toMatchInlineSnapshot(`
"cli/unknown
Expand Down
20 changes: 20 additions & 0 deletions packages/breadc/test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,26 @@ describe('Option Parser', () => {
`);
});

it('should parse negtive boolean option', async () => {
const cli = breadc('cli');
cli.option('--no-open');
cli.command('').action((o) => o);

expect(await cli.run(['--open'])).toMatchInlineSnapshot(`
{
"--": [],
"open": true,
}
`);

expect(await cli.run(['--no-open'])).toMatchInlineSnapshot(`
{
"--": [],
"open": false,
}
`);
});

it('should parse string option', async () => {
const cli = breadc('cli');
cli.option('--flag');
Expand Down

0 comments on commit c94b26b

Please sign in to comment.