4 * Get commandline option values.
5 * @param {Array} args Commandline arguments. Like ["-a=xml", "-b", "--class=new", "--debug"]
6 * @param {object} optNames Map short names to long names. Like {a:"accept", b:"backtrace", c:"class", d:"debug"}.
7 * @return {object} Short names and values. Like {a:"xml", b:true, c:"new", d:true}
9 get
: function(args
, optNames
) {
10 var opt
= {"_": []}; // the unnamed option allows multiple values
11 for (var i
= 0; i
< args
.length
; i
++) {
12 var arg
= new String(args
[i
]);
15 if (arg
.charAt(0) == "-") {
16 if (arg
.charAt(1) == "-") { // it's a longname like --foo
17 arg
= arg
.substring(2);
18 var m
= arg
.split("=");
21 if (typeof value
== "undefined") value
= true;
23 for (var n
in optNames
) { // convert it to a shortname
24 if (name
== optNames
[n
]) {
29 else { // it's a shortname like -f
30 arg
= arg
.substring(1);
31 var m
= arg
.split("=");
34 if (typeof value
== "undefined") value
= true;
36 for (var n
in optNames
) { // find the matching key
37 if (name
== n
|| name
+'[]' == n
) {
43 if (name
.match(/(.+)\[\]$/)) { // it's an array type like n[]
45 if (!opt
[name
]) opt
[name
] = [];
48 if (opt
[name
] && opt
[name
].push
) {
49 opt
[name
].push(value
);
55 else { // not associated with any optname
64 plan(11, "Testing Opt.");
75 "Opt.get is a function."
78 var optNames = {a:"accept", b:"backtrace", c:"class", d:"debug", "e[]":"exceptions"};
79 var t_options = Opt.get(["-a=xml", "-b", "--class=new", "--debug", "-e=one", "-e=two", "foo", "bar"], optNames);
84 "an option defined with a short name can be accessed by its short name."
90 "an option defined with a short name and no value are true."
96 "an option defined with a long name can be accessed by its short name."
102 "an option defined with a long name and no value are true."
108 "an option that can accept multiple values is defined."
114 "an option that can accept multiple values can have more than one value."
120 "an option that can accept multiple values can be accessed as an array."
126 "the property '_' is defined for unnamed options."
132 "the property '_' can be accessed as an array."