Skip to content

Commit

Permalink
feat(breadc): parse boolean options value
Browse files Browse the repository at this point in the history
  • Loading branch information
yjl9903 committed Oct 18, 2023
1 parent 0495f11 commit c27a2d5
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 1 deletion.
13 changes: 12 additions & 1 deletion packages/breadc/src/parser/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export function parseOption(
): TreeNode | false {
const o = token.option();
const [key, rawV] = o.split('=');

if (context.options.has(key)) {
const option = context.options.get(key)!;
const name = camelCase(option.name);
Expand All @@ -45,7 +46,17 @@ export function parseOption(
return option.parse(cursor, token, context);
} else if (option.type === 'boolean') {
// Parse boolean option
context.result.options[name] = !key.startsWith('no-') ? true : false;
const negative = key.startsWith('no-');
if (
rawV === undefined ||
['true', 'yes', 't', 'y'].includes(rawV.toLowerCase())
) {
context.result.options[name] = !negative ? true : false;
} else if (['false', 'no', 'f', 'n'].includes(rawV.toLowerCase())) {
context.result.options[name] = !negative ? false : true;
} else {
throw new ParseError(`Unexpected value ${rawV} for ${option.format}`);
}
} else if (option.type === 'string') {
// Parse string option
if (rawV !== undefined) {
Expand Down
76 changes: 76 additions & 0 deletions packages/breadc/test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,82 @@ describe('Option Parser', () => {
`);
});

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

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

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

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

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

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

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

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

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

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

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

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

0 comments on commit c27a2d5

Please sign in to comment.