forked from subtleGradient/tilde-bin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subtle-argv-parser.js
60 lines (49 loc) · 1.73 KB
/
subtle-argv-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
54
55
56
57
function ArgOptions(args){
/**
* @author Thomas Aylott <[email protected]>
* @copyright 2011 Sencha Labs Foundation
*/
args = args.slice(0) // clone, for safety
var argo = []
var isArg = /^--?(no-)?(?=\w)(.*)$/i
var lastArgKey, thisArgKey
for (var index=0; index < args.length; index++) {
if (thisArgKey = args[index].match(isArg)) {
argo[thisArgKey[2]] = !thisArgKey[1]
}
else if (lastArgKey) {
argo[lastArgKey] = args[index]
}
else {
argo.push(args[index])
}
lastArgKey = thisArgKey && thisArgKey[2]
}
return argo
}
////////////////////////////////////////////////////////////////////////////////
// TEST
var argv = []
var argo = ArgOptions(argv)
console.assert(Object.keys(argo).length == 0)
argv = ['--key','value']
argo = ArgOptions(argv)
console.assert(!!argo.key, 'should set key')
console.assert(argo.key == 'value', 'should set value')
argv = ['howdy','--key','value']
argo = ArgOptions(argv)
console.assert(!!argo.key, 'should set key')
console.assert(argo.key == 'value', 'should set value')
console.assert(argo[0] == 'howdy', 'should keep other args')
argv = ['--key','value','howdy','-y']
argo = ArgOptions(argv)
console.assert(!!argo.key, 'should set key')
console.assert(argo.key == 'value', 'should set value')
console.assert(argo[0] == 'howdy', 'should keep other args')
console.assert(argo.y == true, 'should set booleans')
argv = ['--key','value','howdy','--no-y']
argo = ArgOptions(argv)
console.assert(argo.y == false, 'should allow false booleans')
argv = ['--key','value','howdy','-y','--no-y']
argo = ArgOptions(argv)
console.assert(argo.y == false, 'should override multiple')