forked from jairajs89/zerver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflags.js
108 lines (83 loc) · 1.88 KB
/
flags.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
var path = require('path'),
shellParse = require('shell-quote').parse;
var FLAG_MATCHER = /^(\w+)(?:\=(\S*))?$/,
FUNC_MATCHER = /^[^\(]*\(([^\)]*)/;
var flagHandlers = {},
argHandlers = [];
exports.add = function (flag, handler) {
if ( Array.isArray(flag) ) {
flag.forEach(function (singleFlag) {
exports.add(singleFlag, handler);
});
return;
}
flagHandlers[flag] = handler;
};
exports.arg = function (arg, handler) {
argHandlers.push([arg, handler]);
};
exports.run = function (defaultArgString) {
var args = 0;
var defaultArgs = [];
if (defaultArgString) {
defaultArgs = shellParse(defaultArgString);
console.log("Environment options: " + defaultArgs.join(", "));
}
// defaults go first, so they get overriden by manually specified options
var argv = defaultArgs.concat(process.argv.slice(2));
argv.forEach(function (arg) {
if (arg[0] !== '-') {
try {
argHandlers[args++][1](arg);
}
catch (err) {
usageError();
}
}
else if (arg[1] === '-') {
var match = FLAG_MATCHER.exec( arg.substr(2) );
if (match) {
try {
flagHandlers[ match[1] ]( match[2] );
}
catch (err) {
usageError();
}
}
else {
usageError();
}
}
else {
Array.prototype.slice.call( arg.substr(1) ).forEach(function (flag) {
try {
flagHandlers[flag]();
}
catch (err) {
usageError();
}
});
}
});
};
function usageError () {
var usage = 'Usage: ' + path.basename( process.argv[1] ),
match;
for (var flag in flagHandlers) {
match = FUNC_MATCHER.exec( flagHandlers[flag] );
if (match && match[1]) {
usage += ' [--' + flag + '=VALUE]';
}
else if (flag.length > 1) {
usage += ' [--' + flag + ']';
}
else {
usage += ' [-' + flag + ']';
}
}
for (var i=0, len=argHandlers.length; i<len; i++) {
usage += ' ['+argHandlers[i][0]+']';
}
console.error(usage);
process.exit(1);
}