-
Notifications
You must be signed in to change notification settings - Fork 0
/
Getopt.js
73 lines (61 loc) · 1.88 KB
/
Getopt.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
var Usage = require("./Usage")
, getopt = require("posix-getopt");
var Getopt = exports = module.exports = function(name, options)
{
options = options || {};
var usage = this.usage = new Usage(name, options);
this.options = {};
this.args = {};
this.hasArgs = false;
};
Getopt.prototype.addOption = function(c, options, cb)
{
if (arguments.length === 2 && typeof options === "function") {
cb = options;
options = {};
} else {
options = options || {};
}
options.handler = cb;
this.usage.addOption(c, options);
this.options[c] = options;
return this;
};
Getopt.prototype.addArgument = function(name, options)
{
this.usage.addArgument(name, options);
this.args[name] = options;
this.hasArgs = true;
return this;
};
Getopt.prototype.parse = function(argv)
{
var parser = new getopt.BasicParser(this.usage.getGetoptSpec(), argv)
, options = {}
, args = []
, opt;
while ((opt = parser.getopt()) !== undefined) {
if (this.options[opt.option]) {
var option = this.options[opt.option]
, name = option.name || opt.option
, hasArg = !!option.argumentName;
if (hasArg)
options[name] = opt.optarg;
else
options[name] = true;
if (option.handler)
option.handler(name, options[name]);
} else {
usage.showUsage("Unknown option '"+opt.option+"'", 254);
}
}
args = argv.slice(parser.optind());
if (this.hasArgs) {
if (args.length === 0) {
this.usage.showUsage("Requires at least one argument", 253);
} else if (!this.args.hasOwnProperty(args[0])) {
this.usage.showUsage("Unknown non option argument", 252);
}
}
return {options:options, arguments:args};
};