-
Notifications
You must be signed in to change notification settings - Fork 0
/
arg-to-object.js
83 lines (71 loc) · 1.69 KB
/
arg-to-object.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const search = require('prefix-search').search
const splitargs = require('splitargs')
const fmt = require('util').format
function JSONParse(str) {
// we'll parse 3 types, valid json, number, and string
str = str.trim()
var c = str[0] // test 1st character
if(c == '[' || c == '{') {
try {
return JSON.parse(str)
} catch(e) {
return eval(fmt("(%s)", str))
}
} else {
var val = Number(str)
if(isNaN(val)) {
switch(str.toLowerCase()) {
case 'true': return true
case 'false': return false
default: return str
}
} else {
return val
}
}
}
function asValue(data, length) {
var val = null
if(length == 0)
val = true
else if(length == 1)
val = JSONParse(data[0])
else
val = data.map(JSONParse)
return val
}
function resolveKey(key, keys) {
key = key.substr( key.lastIndexOf('-') + 1 )
if(keys.length) {
var i = search(key, keys)
if(~i) key = keys[i]
}
return key
}
// parse argv into [[key, val]] array
function parse(argv, obj) {
if(typeof argv === 'string') {
argv = splitargs(argv)
} else if(argv && !Array.isArray(argv)) {
obj = argv
argv = null
}
obj = obj ? Object.assign({}, obj) : {} // todo check this
argv = argv || process.argv
var keys = Object.keys(obj)
var len = argv.length
var i = 0
var k = 0
while(i < len) {
if(argv[i].startsWith('-')) {
k = i++
for(; i < len && !argv[i].startsWith('-'); ++i);
var key = resolveKey(argv[k], keys)
var data = argv.slice(k+1, i)
var data_length = data.length
obj[key] = asValue(data, data_length)
} else i++
}
return obj
}
module.exports.parse = parse