Toy parser of command line arguments. Part of the "toys" collection.
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat: Support key=value arguments

Unlike flags, key=value arguments allow the association of arbitrary string
values to named keys.

To set a value on a named key, pass an argument of the type `key=value`:

```bash
$ node command first=1 second=2 third=three
```

This will set the following values on the named keys:

- first: "1"
- second: "2"
- third: "three"

Note that there is no attempt of parsing the values at all so far.

Also, the key name is not allowed to be empty, the following argument will be
silently ignored:

```bash
$ node command =some-value
```

+23 -7
+10 -7
src/pargser.ts
··· 1 1 export function pargser(argv: string[]) { 2 2 const parsedArguments: Record<string, unknown> = {}; 3 - const flags: string[] = []; 4 3 5 4 argv.forEach((argument) => { 6 5 if (argument.startsWith('--')) { 7 - flags.push(argument.slice(2)); 6 + parsedArguments[argument.slice(2)] = true; 8 7 } else if (argument.startsWith('-')) { 9 - flags.push(...argument.slice(1).split('')); 8 + const flags = argument.slice(1).split(''); 9 + flags.forEach((flag) => { 10 + parsedArguments[flag] = true; 11 + }); 12 + } else if (argument.includes('=')) { 13 + const [name, value] = argument.split('='); 14 + if (name) { 15 + parsedArguments[name] = value; 16 + } 10 17 } 11 - }); 12 - 13 - flags.forEach((flag) => { 14 - parsedArguments[flag] = true; 15 18 }); 16 19 17 20 return parsedArguments;
+13
test/pargser.test.ts
··· 38 38 thirdly: true, 39 39 }); 40 40 }); 41 + 42 + it('should support key=value arguments', () => { 43 + expect(pargser(['node', 'program.js', 'foo=bar', 'baz=quux'])).toEqual({ 44 + foo: 'bar', 45 + baz: 'quux', 46 + }); 47 + }); 48 + 49 + it('should ignore empty keys', () => { 50 + expect(pargser(['node', 'program.js', 'foo=bar', '=baz'])).toEqual({ 51 + foo: 'bar', 52 + }); 53 + }); 41 54 });