-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (57 loc) · 1.4 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
/**
* Returns an object with parsed CLI input options
* - args: {array of strings},
* - opts: {array of objects},
* - raw: {unparsed input args}
*
* @return {object}
*/
// TODO: break combined short flags to individual (-dv into -d and -c)
var _cleanUpOptionName = function (str) {
if (str[0] === '-' && str[1] === '-') {
return str.substr(2);
} else if (str[0] === '-') {
return str.substr(1);
} else {
return str;
}
}
var clarg = function (argsIn) {
var rawArgs = argsIn || process.argv.slice(2);
var reachedOpts = false;
var rtn = {
args: [],
opts: {},
raw: rawArgs
}
for (var i = 0; i < rawArgs.length; i++) {
var isOption = false;
var current = rawArgs[i];
// detect opts
if (current[0] === '-') {
reachedOpts = true;
isOption = true;
}
// parse all arguments
if (!reachedOpts) {
rtn.args.push(current);
} else {
if (isOption) {
// set option to true
var curName = _cleanUpOptionName(current);
var curNameSplit = curName.split('=');
if (curNameSplit[1]) {
rtn.opts[curNameSplit[0]] = curNameSplit[1];
} else {
rtn.opts[curNameSplit[0]] = true;
}
} else {
// or set a value to it
var prevName = _cleanUpOptionName(rawArgs[i-1]);
rtn.opts[prevName] = current;
}
}
}
return rtn;
};
module.exports = clarg;