-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
106 lines (84 loc) · 2.07 KB
/
index.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*!
* dargs-fork <https://github.com/tunnckoCore/dargs-fork>
*
* Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
* Released under the MIT license.
*/
'use strict'
const match = (arr, val) => {
return arr.some(x => {
return x instanceof RegExp ? x.test(val) : x === val
})
}
module.exports = function dargsFork (input, opts) {
const args = []
let extraArgs = []
opts = Object.assign({
useEquals: true
}, opts)
const makeArg = (key, val) => {
let prefix = key.length === 1 ? '-' : '--'
let theKey = opts.allowCamelCase
? key
: key.replace(/[A-Z]/g, '-$&').toLowerCase()
key = prefix + theKey
if (opts.useEquals) {
args.push(key + (val ? `=${val}` : ''))
} else {
args.push(key)
if (val) {
args.push(val)
}
}
}
const makeAliasArg = (key, val) => {
args.push(`-${key}`)
/* istanbul ignore next */
if (val) {
args.push(val)
}
}
// TODO: use for-of loop and Object.entries when targeting Node.js 6
Object.keys(input).forEach(key => {
const val = input[key]
let pushArg = makeArg
if (Array.isArray(opts.excludes) && match(opts.excludes, key)) {
return
}
if (Array.isArray(opts.includes) && !match(opts.includes, key)) {
return
}
if (typeof opts.aliases === 'object' && opts.aliases[key]) {
key = opts.aliases[key]
pushArg = makeAliasArg
}
if (key === '_') {
if (!Array.isArray(val)) {
throw new TypeError(`Expected key \`_\` to be Array, got ${typeof val}`)
}
extraArgs = val
return
}
if (val === true) {
pushArg(key, '')
}
if (val === false && !opts.ignoreFalse) {
pushArg(`no-${key}`)
}
if (typeof val === 'string') {
pushArg(key, val)
}
if (typeof val === 'number' && !Number.isNaN(val)) {
pushArg(key, String(val))
}
if (Array.isArray(val)) {
val.forEach(arrVal => {
pushArg(key, arrVal)
})
}
})
for (const x of extraArgs) {
args.push(String(x))
}
return args
}