-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.js
More file actions
74 lines (64 loc) · 1.67 KB
/
parser.js
File metadata and controls
74 lines (64 loc) · 1.67 KB
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
const cleanFlag = flag => flag.substr(flag[1] === "-" ? 2 : 1)
const tryParse = value => {
const number = Number.parseFloat(value)
if (!isNaN(number)) {
return number
}
const lowerValue = value.toLowerCase()
if (lowerValue === "true") {
return true
}
if (lowerValue === "false") {
return false
}
return value
}
module.exports = input => {
if (typeof input === "string") {
input = ["", "", ...input.split(" ").filter(e => e)]
}
input = input.reduce((acc, e) => {
if (e !== "=") {
if (e.includes("=")) {
acc.push(...e.split("="))
} else {
acc.push(e)
}
}
return acc
}, [])
input = input.reduce((acc, e) => {
if (e.length > 2 && e[0] === "-" && e[1] !== "-" && isNaN(Number.parseFloat(e))) {
e.substr(1, e.length - 1).split("").forEach(e => {
acc.push(`-${e}`, "true")
})
} else {
acc.push(e)
}
return acc
}, [])
const argv = { _: [] }
for (let i = 2; i < input.length; i++) {
const e = input[i]
if (e[0] !== "-" || !isNaN(Number.parseFloat(e))) {
const prevE = input[i - 1]
if (prevE[0] === "-") {
argv[cleanFlag(prevE)] = tryParse(e)
} else {
argv._.push(tryParse(e))
}
} else {
const index = e.indexOf("=")
if (index === -1) {
const cleanE = cleanFlag(e)
cleanE.substr(0, 3).toLowerCase() !== "no-" ? argv[cleanE] = true : argv[cleanE.substr(3, cleanE.length)] = false
} else {
const key = e.substr(0, index)
input[i] = key
argv[cleanFlag(key)] = null
input.splice(i + 1, 0, e.substr(index + 1, e.length))
}
}
}
return argv
}