Skip to content

Commit

Permalink
feat: unknown flag values to be passed in explicitly (#13)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: values must be explicitly passed into unknown flags
  • Loading branch information
privatenumber committed Oct 27, 2022
1 parent 2c5bcfd commit d4b921d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 22 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,10 @@ $ node ./cli --someString hello --some-string world
```

### Unknown flags
When unrecognized flags are passed in, they are either interpreted as a string or boolean depending on usage. Unknown flags are not converted to camelCase to allow for accurate error handling.
When unrecognized flags are passed in, they are interpreted as a boolean, or a string if explicitly passed in. Unknown flags are not converted to camelCase to allow for accurate error handling.

```sh
$ node ./cli --unknown-flag --unknown-flag 2
$ node ./cli --unknown-flag --unknown-flag=2
```

This outputs the following:
Expand Down
11 changes: 4 additions & 7 deletions src/type-flag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,11 @@ export function typeFlag<Schemas extends Flags>(
parsed.unknownFlags[flagName] = [];
}

if (flagValue !== undefined) {
parsed.unknownFlags[flagName].push(flagValue);
} else {
setValueOnPreviousFlag = (value = true) => {
parsed.unknownFlags[flagName].push(value);
setValueOnPreviousFlag = undefined;
};
if (flagValue === undefined) {
flagValue = true;
}

parsed.unknownFlags[flagName].push(flagValue);
};

for (let i = 0; i < argv.length; i += 1) {
Expand Down
23 changes: 10 additions & 13 deletions tests/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,19 +293,17 @@ describe('Parsing', ({ describe, test }) => {
const parsed = typeFlag(
{},
[
'--unknownFlag',
'arg1',
'--unknownFlag=false',
'--unknownFlag=',
'a',
'--unknownFlag',
'arg2',
'-u',
'4',
'-u=a',
'--unknownString',
'hello',
'--unknownString',
'arg3',
'-u=value',
'-3',
'-sdf',
'4',
'arg4',
'-ff=a',
'--kebab-case',
],
Expand All @@ -320,18 +318,17 @@ describe('Parsing', ({ describe, test }) => {
};

expect<UnknownFlags>(parsed.unknownFlags).toStrictEqual({
unknownFlag: ['false', '', true],
u: ['4', 'a'],
unknownFlag: [true, 'false', ''],
u: [true, 'value'],
3: [true],
s: [true],
d: [true],
f: ['4', true, 'a'],
unknownString: ['hello', true],
f: [true, true, 'a'],
'kebab-case': [true],
});
expect<string[]>(parsed._).toStrictEqual(
Object.assign(
['a'],
['arg1', 'arg2', 'arg3', 'arg4'],
{ '--': [] },
),
);
Expand Down

0 comments on commit d4b921d

Please sign in to comment.