Skip to content

Commit 1f11e73

Browse files
authored
Initial work on parseArgs (#1)
* starting with dash dash * arg work * use strict in test file
1 parent 957d8d9 commit 1f11e73

File tree

4 files changed

+698
-2
lines changed

4 files changed

+698
-2
lines changed

index.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
'use strict';
2+
3+
const parseArgs = (
4+
argv = process.argv.slice(require.main ? 2 : 1),
5+
options = {}
6+
) => {
7+
if (typeof options !== 'object' || options === null) {
8+
throw new Error('Whoops!')
9+
}
10+
11+
let result = {
12+
args: {},
13+
values: {},
14+
positionals: []
15+
}
16+
17+
let pos = 0
18+
while (pos < argv.length) {
19+
let arg = argv[pos]
20+
21+
if (arg.startsWith('-')) {
22+
// Everything after a bare '--' is considered a positional argument
23+
// and is returned verbatim
24+
if (arg === '--') {
25+
result.positionals.push(...argv.slice(++pos))
26+
27+
return result
28+
}
29+
// look for shortcodes: -fXzy
30+
else if (arg.charAt(1) !== '-') {
31+
throw new Error('What are we doing with shortcodes!?!')
32+
}
33+
34+
// Any number of leading dashes are allowed
35+
// remove all leading dashes
36+
arg = arg.replace(/^-+/, '')
37+
38+
if (arg.includes('=')) {
39+
const argParts = arg.split('=')
40+
41+
result.args[argParts[0]] = true
42+
if (options.withValue) {
43+
result.values[argParts[0]] = argParts[1]
44+
}
45+
}
46+
else {
47+
result.args[arg] = true
48+
49+
}
50+
}
51+
52+
pos++
53+
}
54+
55+
return result
56+
}
57+
58+
module.exports = {
59+
parseArgs
60+
}

0 commit comments

Comments
 (0)