Skip to content

Commit a92600f

Browse files
shadowspawnljharbaaronccasanova
authored
refactor!: parsing, revisit short option groups, add support for combined short and value (#75)
1) Refactor parsing to use independent blocks of code, rather than nested cascading context. This makes it easier to reason about the behaviour. 2) Split out small pieces of logic to named routines to improve readability, and allow extra documentation and examples without cluttering the parsing. (Thanks to @aaronccasanova for inspiration.) 3) Existing tests untouched to make it clear that the tested functionality has not changed. 4) Be more explicit about short option group expansion, and ready to throw error in strict mode for string option in the middle of the argument. (See #11 and #74.) 5) Add support for short option combined with value (without intervening `=`). This is what Commander and Open Group Utility Conventions do, but is _not_ what Yargs does. I don't want to block PR on this and happy to comment it out for further discussion if needed. (I have found some interesting variations in the wild.) [Edit: see also #78] 6) Add support for multiple unit tests files. Expand tests from 33 to 113, but many for internal routines rather than testing exposed API. 7) Added `.editorconfig` file Co-authored-by: Jordan Harband <ljharb@gmail.com> Co-authored-by: Aaron Casanova <32409546+aaronccasanova@users.noreply.github.com>
1 parent b412095 commit a92600f

15 files changed

+872
-77
lines changed

.editorconfig

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# EditorConfig is awesome: http://EditorConfig.org
2+
3+
# top-most EditorConfig file
4+
root = true
5+
6+
[*]
7+
end_of_line = lf
8+
insert_final_newline = true
9+
indent_style = space
10+
indent_size = 2
11+
tab_width = 2
12+
# trim_trailing_whitespace = true

index.js

+86-75
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,16 @@
22

33
const {
44
ArrayPrototypeConcat,
5-
ArrayPrototypeFind,
65
ArrayPrototypeForEach,
6+
ArrayPrototypeShift,
77
ArrayPrototypeSlice,
8-
ArrayPrototypeSplice,
98
ArrayPrototypePush,
109
ObjectHasOwn,
1110
ObjectEntries,
1211
StringPrototypeCharAt,
1312
StringPrototypeIncludes,
1413
StringPrototypeIndexOf,
1514
StringPrototypeSlice,
16-
StringPrototypeStartsWith,
1715
} = require('./primordials');
1816

1917
const {
@@ -24,6 +22,16 @@ const {
2422
validateBoolean,
2523
} = require('./validators');
2624

25+
const {
26+
findLongOptionForShort,
27+
isLoneLongOption,
28+
isLoneShortOption,
29+
isLongOptionAndValue,
30+
isOptionValue,
31+
isShortOptionAndValue,
32+
isShortOptionGroup
33+
} = require('./utils');
34+
2735
function getMainArgs() {
2836
// This function is a placeholder for proposed process.mainArgs.
2937
// Work out where to slice process.argv for user supplied arguments.
@@ -116,86 +124,89 @@ const parseArgs = ({
116124
positionals: []
117125
};
118126

119-
let pos = 0;
120-
while (pos < args.length) {
121-
let arg = args[pos];
122-
123-
if (StringPrototypeStartsWith(arg, '-')) {
124-
if (arg === '-') {
125-
// '-' commonly used to represent stdin/stdout, treat as positional
126-
result.positionals = ArrayPrototypeConcat(result.positionals, '-');
127-
++pos;
128-
continue;
129-
} else if (arg === '--') {
130-
// Everything after a bare '--' is considered a positional argument
131-
// and is returned verbatim
132-
result.positionals = ArrayPrototypeConcat(
133-
result.positionals,
134-
ArrayPrototypeSlice(args, ++pos)
135-
);
136-
return result;
137-
} else if (StringPrototypeCharAt(arg, 1) !== '-') {
138-
// Look for shortcodes: -fXzy and expand them to -f -X -z -y:
139-
if (arg.length > 2) {
140-
for (let i = 2; i < arg.length; i++) {
141-
const shortOption = StringPrototypeCharAt(arg, i);
142-
// Add 'i' to 'pos' such that short options are parsed in order
143-
// of definition:
144-
ArrayPrototypeSplice(args, pos + (i - 1), 0, `-${shortOption}`);
145-
}
146-
}
127+
let remainingArgs = ArrayPrototypeSlice(args);
128+
while (remainingArgs.length > 0) {
129+
const arg = ArrayPrototypeShift(remainingArgs);
130+
const nextArg = remainingArgs[0];
131+
132+
// Check if `arg` is an options terminator.
133+
// Guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
134+
if (arg === '--') {
135+
// Everything after a bare '--' is considered a positional argument.
136+
result.positionals = ArrayPrototypeConcat(
137+
result.positionals,
138+
remainingArgs
139+
);
140+
break; // Finished processing args, leave while loop.
141+
}
147142

148-
arg = StringPrototypeCharAt(arg, 1); // short
143+
if (isLoneShortOption(arg)) {
144+
// e.g. '-f'
145+
const shortOption = StringPrototypeCharAt(arg, 1);
146+
const longOption = findLongOptionForShort(shortOption, options);
147+
let optionValue;
148+
if (options[longOption]?.type === 'string' && isOptionValue(nextArg)) {
149+
// e.g. '-f', 'bar'
150+
optionValue = ArrayPrototypeShift(remainingArgs);
151+
}
152+
storeOptionValue(options, longOption, optionValue, result);
153+
continue;
154+
}
149155

150-
const [longOption] = ArrayPrototypeFind(
151-
ObjectEntries(options),
152-
([, optionConfig]) => optionConfig.short === arg
153-
) || [];
156+
if (isShortOptionGroup(arg, options)) {
157+
// Expand -fXzy to -f -X -z -y
158+
const expanded = [];
159+
for (let index = 1; index < arg.length; index++) {
160+
const shortOption = StringPrototypeCharAt(arg, index);
161+
const longOption = findLongOptionForShort(shortOption, options);
162+
if (options[longOption]?.type !== 'string' ||
163+
index === arg.length - 1) {
164+
// Boolean option, or last short in group. Well formed.
165+
ArrayPrototypePush(expanded, `-${shortOption}`);
166+
} else {
167+
// String option in middle. Yuck.
168+
// ToDo: if strict then throw
169+
// Expand -abfFILE to -a -b -fFILE
170+
ArrayPrototypePush(expanded, `-${StringPrototypeSlice(arg, index)}`);
171+
break; // finished short group
172+
}
173+
}
174+
remainingArgs = ArrayPrototypeConcat(expanded, remainingArgs);
175+
continue;
176+
}
154177

155-
arg = longOption ?? arg;
178+
if (isShortOptionAndValue(arg, options)) {
179+
// e.g. -fFILE
180+
const shortOption = StringPrototypeCharAt(arg, 1);
181+
const longOption = findLongOptionForShort(shortOption, options);
182+
const optionValue = StringPrototypeSlice(arg, 2);
183+
storeOptionValue(options, longOption, optionValue, result);
184+
continue;
185+
}
156186

157-
// ToDo: later code tests for `=` in arg and wrong for shorts
158-
} else {
159-
arg = StringPrototypeSlice(arg, 2); // remove leading --
187+
if (isLoneLongOption(arg)) {
188+
// e.g. '--foo'
189+
const longOption = StringPrototypeSlice(arg, 2);
190+
let optionValue;
191+
if (options[longOption]?.type === 'string' && isOptionValue(nextArg)) {
192+
// e.g. '--foo', 'bar'
193+
optionValue = ArrayPrototypeShift(remainingArgs);
160194
}
195+
storeOptionValue(options, longOption, optionValue, result);
196+
continue;
197+
}
161198

162-
if (StringPrototypeIncludes(arg, '=')) {
163-
// Store option=value same way independent of `type: "string"` as:
164-
// - looks like a value, store as a value
165-
// - match the intention of the user
166-
// - preserve information for author to process further
167-
const index = StringPrototypeIndexOf(arg, '=');
168-
storeOptionValue(
169-
options,
170-
StringPrototypeSlice(arg, 0, index),
171-
StringPrototypeSlice(arg, index + 1),
172-
result);
173-
} else if (pos + 1 < args.length &&
174-
!StringPrototypeStartsWith(args[pos + 1], '-')
175-
) {
176-
// `type: "string"` option should also support setting values when '='
177-
// isn't used ie. both --foo=b and --foo b should work
178-
179-
// If `type: "string"` option is specified, take next position argument
180-
// as value and then increment pos so that we don't re-evaluate that
181-
// arg, else set value as undefined ie. --foo b --bar c, after setting
182-
// b as the value for foo, evaluate --bar next and skip 'b'
183-
const val = options[arg] && options[arg].type === 'string' ?
184-
args[++pos] :
185-
undefined;
186-
storeOptionValue(options, arg, val, result);
187-
} else {
188-
// Cases when an arg is specified without a value, example
189-
// '--foo --bar' <- 'foo' and 'bar' flags should be set to true and
190-
// save value as undefined
191-
storeOptionValue(options, arg, undefined, result);
192-
}
193-
} else {
194-
// Arguments without a dash prefix are considered "positional"
195-
ArrayPrototypePush(result.positionals, arg);
199+
if (isLongOptionAndValue(arg)) {
200+
// e.g. --foo=bar
201+
const index = StringPrototypeIndexOf(arg, '=');
202+
const longOption = StringPrototypeSlice(arg, 2, index);
203+
const optionValue = StringPrototypeSlice(arg, index + 1);
204+
storeOptionValue(options, longOption, optionValue, result);
205+
continue;
196206
}
197207

198-
pos++;
208+
// Anything left is a positional
209+
ArrayPrototypePush(result.positionals, arg);
199210
}
200211

201212
return result;

package.json

+6-2
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@
33
"version": "0.3.0",
44
"description": "Polyfill of future proposal for `util.parseArgs()`",
55
"main": "index.js",
6+
"exports": {
7+
".": "./index.js",
8+
"./package.json": "./package.json"
9+
},
610
"scripts": {
7-
"coverage": "c8 --check-coverage node test/index.js",
8-
"test": "c8 node test/index.js",
11+
"coverage": "c8 --check-coverage tape 'test/*.js'",
12+
"test": "c8 tape 'test/*.js'",
913
"posttest": "eslint .",
1014
"fix": "npm run posttest -- --fix"
1115
},

test/dash.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict';
2+
/* eslint max-len: 0 */
3+
4+
const test = require('tape');
5+
const { parseArgs } = require('../index.js');
6+
7+
// The use of `-` as a positional is specifically mentioned in the Open Group Utility Conventions.
8+
// The interpretation is up to the utility, and for a file positional (operand) the examples are
9+
// '-' may stand for standard input (or standard output), or for a file named -.
10+
// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
11+
//
12+
// A different usage and example is `git switch -` to switch back to the previous branch.
13+
14+
test("dash: when args include '-' used as positional then result has '-' in positionals", (t) => {
15+
const passedArgs = ['-'];
16+
const expected = { flags: {}, values: {}, positionals: ['-'] };
17+
18+
const result = parseArgs({ args: passedArgs });
19+
20+
t.deepEqual(result, expected);
21+
t.end();
22+
});
23+
24+
// If '-' is a valid positional, it is symmetrical to allow it as an option value too.
25+
test("dash: when args include '-' used as space-separated option value then result has '-' in option value", (t) => {
26+
const passedArgs = ['-v', '-'];
27+
const passedOptions = { v: { type: 'string' } };
28+
const expected = { flags: { v: true }, values: { v: '-' }, positionals: [] };
29+
30+
const result = parseArgs({ args: passedArgs, options: passedOptions });
31+
32+
t.deepEqual(result, expected);
33+
t.end();
34+
});

test/find-long-option-for-short.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
/* eslint max-len: 0 */
3+
4+
const test = require('tape');
5+
const { findLongOptionForShort } = require('../utils.js');
6+
7+
test('findLongOptionForShort: when passed empty options then returns short', (t) => {
8+
t.equal(findLongOptionForShort('a', {}), 'a');
9+
t.end();
10+
});
11+
12+
test('findLongOptionForShort: when passed short not present in options then returns short', (t) => {
13+
t.equal(findLongOptionForShort('a', { foo: { short: 'f', type: 'string' } }), 'a');
14+
t.end();
15+
});
16+
17+
test('findLongOptionForShort: when passed short present in options then returns long', (t) => {
18+
t.equal(findLongOptionForShort('a', { alpha: { short: 'a' } }), 'alpha');
19+
t.end();
20+
});

test/is-lone-long-option.js

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
'use strict';
2+
/* eslint max-len: 0 */
3+
4+
const test = require('tape');
5+
const { isLoneLongOption } = require('../utils.js');
6+
7+
test('isLoneLongOption: when passed short option then returns false', (t) => {
8+
t.false(isLoneLongOption('-s'));
9+
t.end();
10+
});
11+
12+
test('isLoneLongOption: when passed short option group then returns false', (t) => {
13+
t.false(isLoneLongOption('-abc'));
14+
t.end();
15+
});
16+
17+
test('isLoneLongOption: when passed lone long option then returns true', (t) => {
18+
t.true(isLoneLongOption('--foo'));
19+
t.end();
20+
});
21+
22+
test('isLoneLongOption: when passed single character long option then returns true', (t) => {
23+
t.true(isLoneLongOption('--f'));
24+
t.end();
25+
});
26+
27+
test('isLoneLongOption: when passed long option and value then returns false', (t) => {
28+
t.false(isLoneLongOption('--foo=bar'));
29+
t.end();
30+
});
31+
32+
test('isLoneLongOption: when passed empty string then returns false', (t) => {
33+
t.false(isLoneLongOption(''));
34+
t.end();
35+
});
36+
37+
test('isLoneLongOption: when passed plain text then returns false', (t) => {
38+
t.false(isLoneLongOption('foo'));
39+
t.end();
40+
});
41+
42+
test('isLoneLongOption: when passed single dash then returns false', (t) => {
43+
t.false(isLoneLongOption('-'));
44+
t.end();
45+
});
46+
47+
test('isLoneLongOption: when passed double dash then returns false', (t) => {
48+
t.false(isLoneLongOption('--'));
49+
t.end();
50+
});
51+
52+
// This is a bit bogus, but simple consistent behaviour: long option follows double dash.
53+
test('isLoneLongOption: when passed arg starting with triple dash then returns true', (t) => {
54+
t.true(isLoneLongOption('---foo'));
55+
t.end();
56+
});
57+
58+
// This is a bit bogus, but simple consistent behaviour: long option follows double dash.
59+
test("isLoneLongOption: when passed '--=' then returns true", (t) => {
60+
t.true(isLoneLongOption('--='));
61+
t.end();
62+
});

test/is-lone-short-option.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
/* eslint max-len: 0 */
3+
4+
const test = require('tape');
5+
const { isLoneShortOption } = require('../utils.js');
6+
7+
test('isLoneShortOption: when passed short option then returns true', (t) => {
8+
t.true(isLoneShortOption('-s'));
9+
t.end();
10+
});
11+
12+
test('isLoneShortOption: when passed short option group (or might be short and value) then returns false', (t) => {
13+
t.false(isLoneShortOption('-abc'));
14+
t.end();
15+
});
16+
17+
test('isLoneShortOption: when passed long option then returns false', (t) => {
18+
t.false(isLoneShortOption('--foo'));
19+
t.end();
20+
});
21+
22+
test('isLoneShortOption: when passed long option with value then returns false', (t) => {
23+
t.false(isLoneShortOption('--foo=bar'));
24+
t.end();
25+
});
26+
27+
test('isLoneShortOption: when passed empty string then returns false', (t) => {
28+
t.false(isLoneShortOption(''));
29+
t.end();
30+
});
31+
32+
test('isLoneShortOption: when passed plain text then returns false', (t) => {
33+
t.false(isLoneShortOption('foo'));
34+
t.end();
35+
});
36+
37+
test('isLoneShortOption: when passed single dash then returns false', (t) => {
38+
t.false(isLoneShortOption('-'));
39+
t.end();
40+
});
41+
42+
test('isLoneShortOption: when passed double dash then returns false', (t) => {
43+
t.false(isLoneShortOption('--'));
44+
t.end();
45+
});

0 commit comments

Comments
 (0)