-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
116 lines (91 loc) · 2.32 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
107
108
109
110
111
112
113
114
115
116
const match = (array, value) =>
array.some(element => (element instanceof RegExp ? element.test(value) : element === value));
export default function dargs(object, options) {
const arguments_ = [];
let extraArguments = [];
let separatedArguments = [];
options = {
useEquals: true,
shortFlag: true,
...options
};
const makeArguments = (key, value) => {
const prefix = options.shortFlag && key.length === 1 ? '-' : '--';
const theKey = (options.allowCamelCase ?
key :
key.replace(/[A-Z]/g, '-$&').toLowerCase());
key = prefix + theKey;
if (options.useEquals) {
arguments_.push(key + (value ? `=${value}` : ''));
} else {
arguments_.push(key);
if (value) {
arguments_.push(value);
}
}
};
const makeAliasArg = (key, value) => {
arguments_.push(`-${key}`);
if (value) {
arguments_.push(value);
}
};
for (let [key, value] of Object.entries(object)) {
let pushArguments = makeArguments;
if (Array.isArray(options.excludes) && match(options.excludes, key)) {
continue;
}
if (Array.isArray(options.includes) && !match(options.includes, key)) {
continue;
}
if (typeof options.aliases === 'object' && options.aliases[key]) {
key = options.aliases[key];
pushArguments = makeAliasArg;
}
if (key === '--') {
if (!Array.isArray(value)) {
throw new TypeError(
`Expected key \`--\` to be Array, got ${typeof value}`
);
}
separatedArguments = value;
continue;
}
if (key === '_') {
if (!Array.isArray(value)) {
throw new TypeError(
`Expected key \`_\` to be Array, got ${typeof value}`
);
}
extraArguments = value;
continue;
}
if (value === true && !options.ignoreTrue) {
pushArguments(key, '');
}
if (value === false && !options.ignoreFalse) {
pushArguments(`no-${key}`);
}
if (typeof value === 'string') {
pushArguments(key, value);
}
if (typeof value === 'number' && !Number.isNaN(value)) {
pushArguments(key, String(value));
}
if (Array.isArray(value)) {
for (const arrayValue of value) {
pushArguments(key, arrayValue);
}
}
}
for (const argument of extraArguments) {
arguments_.push(String(argument));
}
if (separatedArguments.length > 0) {
arguments_.push('--');
}
for (const argument of separatedArguments) {
arguments_.push(String(argument));
}
return arguments_;
}