-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargument_parser.js
53 lines (47 loc) · 1.32 KB
/
argument_parser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function isArg(arg, lookup) {
return lookup.hasOwnProperty(arg)
}
function parseArgs(rawArgs) {
const ARG_MAP = {
LOCAL_DEV: {name: 'LOCAL_DEV'},
PORT: {name: 'PORT', singleValue: true},
IGNORE: {name: 'IGNORE', multiValue: true},
HELP: {name: 'HELP'},
VERSION: {name: 'VERSION'},
QUIET: {name: 'QUIET'}
}
const ARG_LOOKUP = {
'--local-dev': ARG_MAP.LOCAL_DEV,
'-l': ARG_MAP.LOCAL_DEV,
'--port': ARG_MAP.PORT,
'-p': ARG_MAP.PORT,
'--ignore': ARG_MAP.IGNORE,
'-i': ARG_MAP.IGNORE,
'--help': ARG_MAP.HELP,
'-h': ARG_MAP.HELP,
'--version': ARG_MAP.VERSION,
'-v': ARG_MAP.VERSION,
'--quiet': ARG_MAP.QUIET,
'-q': ARG_MAP.QUIET,
}
return [...rawArgs].reduce((collected, rawArg) => {
if (!isArg(rawArg, ARG_LOOKUP) && !collected.length) return collected
const lastArgCollection = collected.slice(-1)[0]
const restArgCollection = collected.slice(0, -1)
return (
isArg(rawArg, ARG_LOOKUP)
? [...collected, [rawArg]]
: [...restArgCollection, [...lastArgCollection, rawArg]]
)
}, []).reduce((argStruct, [arg, ...values]) => ({
...argStruct,
[ARG_LOOKUP[arg].name]: (
values.length === 0
? true
: values.length === 1
? values[0]
: values
)
}), {})
}
module.exports = parseArgs