-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargs.js
71 lines (67 loc) · 2.32 KB
/
args.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
//==============================================================================
// ■ args (args.js)
//------------------------------------------------------------------------------
// Arguments variables manipulation utilities.
//==============================================================================
//------------------------------------------------------------------------------
// ● Text-Flag-Check
//------------------------------------------------------------------------------
function isLongFlag(text) {
return text.startsWith(LONG_PREFIX);
}
function isShortFlag(text) {
return !isLongFlag(text) && text.startsWith(SHORT_PREFIX);
}
function isFlag(text) {
return isLongFlag(text) || isShortFlag(text);
}
//------------------------------------------------------------------------------
// ● Flag-Value
//------------------------------------------------------------------------------
// returns {undefined} if flag is not provided.
// returns {null} if flag is provided without a value (example: --name).
// returns {String} if flag is provided with a value (example: --name ambratolm).
//------------------------------------------------------------------------------
function flagValue(text) {
if (!isFlag(text)) {
throw ERR_NOT_FLAG(text);
}
let index = process.argv.indexOf(text);
if (index < 0) return undefined;
const value = process.argv[index + 1];
return value || null;
}
//------------------------------------------------------------------------------
// ● Get-Options
//------------------------------------------------------------------------------
function getOptions() {
const options = [];
for (const arg of process.argv) {
if (isLongFlag(arg)) {
options.push({
key: arg.substring(LONG_PREFIX.length, arg.length),
value: flagValue(arg),
type: "long",
flag: arg,
});
} else if (isShortFlag(arg)) {
options.push({
key: arg.substring(SHORT_PREFIX.length, arg.length),
value: flagValue(arg),
type: "short",
flag: arg,
});
}
}
return options;
}
//------------------------------------------------------------------------------
// ► Exports
//------------------------------------------------------------------------------
module.exports = {
isLongFlag,
isShortFlag,
isFlag,
flagValue,
getOptions
};