-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseCommand.js
68 lines (54 loc) · 1.28 KB
/
parseCommand.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const peg = require('pegjs')
const def = `
command =
word*
word =
option
/ flag
/ positional
/ whitespace
nitem =
val:[^ \\t\\n\\r]+ { return val.join(''); }
onitem =
val:[^ \\t\\n\\r=]+ { return val.join(''); }
item =
'"' val:[^"]* '"' { return val.join(''); }
/ "'" val:[^']* "'" { return val.join(''); }
/ val:[^ \\t\\n\\r]+ { return val.join(''); }
whitespace =
[ \\t\\n\\r]+ { return {type: 'whitespace'}; }
option =
'--' name:onitem '=' value:item { return {type: 'option', name: name, value: value}; }
/ '-' name:onitem '=' value:item { return {type: 'option', name: name, value: value}; }
flag =
'--' val:nitem { return {type: 'flag', name: val}; }
/ '-' val:nitem { return {type: 'flag', name: val}; }
positional =
val:item { return {type: 'positional', value: val}; }
`
var parser = peg.generate(def);
module.exports = (cmd) => {
ret = {
options: {},
flags: [],
positionals: [],
val: ''
};
ret.val = cmd;
res = parser.parse(cmd);
for (let i of res) {
switch (i.type) {
case 'flag':
ret.flags.push(i.name);
break;
case 'option':
ret.options[i.name] = i.value;
break;
case 'positional':
ret.positionals.push(i.value);
break;
default: break;
}
}
return ret;
}