This repository was archived by the owner on Dec 4, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 877
/
Copy pathparseArgString.js
55 lines (51 loc) · 1.63 KB
/
parseArgString.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
/**
* @dgService parseArgString
* @description
* processes an arg string in 'almost' the same fashion that the command processor does
* and returns an args object in yargs format.
* @kind function
* @param {String} str The arg string to process
* @return {Object} The args parsed into a yargs format.
*/
module.exports = function parseArgString() {
return function parseArgStringImpl(str) {
// regex from npm string-argv
//[^\s'"] Match if not a space ' or "
//+|['] or Match '
//([^']*) Match anything that is not '
//['] Close match if '
//+|["] or Match "
//([^"]*) Match anything that is not "
//["] Close match if "
var rx = /[^\s'"]+|[']([^']*?)[']|["]([^"]*?)["]/gi;
var value = str;
var unnammedArgs = [];
var args = {_: unnammedArgs};
var match, key;
do {
//Each call to exec returns the next regex match as an array
match = rx.exec(value);
if (match !== null) {
//Index 1 in the array is the captured group if it exists
//Index 0 is the matched text, which we use if no captured group exists
var arg = match[2] ? match[2] : (match[1] ? match[1] : match[0]);
if (key) {
args[key] = arg;
key = null;
} else {
if (arg.substr(arg.length - 1) === '=') {
key = arg.substr(0, arg.length - 1);
// remove leading '-' if it exists.
if (key.substr(0, 1) == '-') {
key = key.substr(1);
}
} else {
unnammedArgs.push(arg)
key = null;
}
}
}
} while (match !== null);
return args;
}
}