allowing merged short flags in optparse.coffee, via normalize_arguments

This commit is contained in:
Jeremy Ashkenas
2010-02-25 19:06:08 -05:00
parent 3ae2ebe5ea
commit 406a18067d
2 changed files with 38 additions and 5 deletions

View File

@@ -1,5 +1,5 @@
(function(){
var LONG_FLAG, OPTIONAL, SHORT_FLAG, build_rule, build_rules, op;
var LONG_FLAG, MULTI_FLAG, OPTIONAL, SHORT_FLAG, build_rule, build_rules, normalize_arguments, op;
// Create an OptionParser with a list of valid options, in the form:
// [short-flag (optional), long-flag, description]
// And an optional banner for the usage help.
@@ -17,7 +17,7 @@
options = {
arguments: []
};
args = args.slice(0);
args = normalize_arguments(args);
while (arg = args.shift()) {
is_option = !!(arg.match(LONG_FLAG) || arg.match(SHORT_FLAG));
matched_rule = false;
@@ -61,7 +61,8 @@
};
// Regex matchers for option flags.
LONG_FLAG = /^(--\w[\w\-]+)/;
SHORT_FLAG = /^(-\w+)/;
SHORT_FLAG = /^(-\w)/;
MULTI_FLAG = /^-(\w{2,})/;
OPTIONAL = /\[(.+)\]/;
// Build rules from a list of valid switch tuples in the form:
// [letter-flag, long-flag, help], or [long-flag, help].
@@ -92,4 +93,24 @@
has_argument: !!(match && match[1])
};
};
// Normalize arguments by expanding merged flags into multiple flags.
normalize_arguments = function normalize_arguments(args) {
var _a, _b, _c, _d, arg, l, match, result;
args = args.slice(0);
result = [];
_a = args;
for (_b = 0; _b < _a.length; _b++) {
arg = _a[_b];
if ((match = arg.match(MULTI_FLAG))) {
_c = match[1].split('');
for (_d = 0; _d < _c.length; _d++) {
l = _c[_d];
result.push('-' + l);
}
} else {
result.push(arg);
}
}
return result;
};
})();

View File

@@ -11,7 +11,7 @@ op: exports.OptionParser: (rules, banner) ->
# containing the remaning non-option arguments.
op::parse: (args) ->
options: {arguments: []}
args: args.slice 0
args: normalize_arguments args
while arg: args.shift()
is_option: !!(arg.match(LONG_FLAG) or arg.match(SHORT_FLAG))
matched_rule: no
@@ -36,7 +36,8 @@ op::help: ->
# Regex matchers for option flags.
LONG_FLAG: /^(--\w[\w\-]+)/
SHORT_FLAG: /^(-\w+)/
SHORT_FLAG: /^(-\w)/
MULTI_FLAG: /^-(\w{2,})/
OPTIONAL: /\[(.+)\]/
# Build rules from a list of valid switch tuples in the form:
@@ -57,3 +58,14 @@ build_rule: (letter, flag, description) ->
description: description
has_argument: !!(match and match[1])
}
# Normalize arguments by expanding merged flags into multiple flags.
normalize_arguments: (args) ->
args: args.slice 0
result: []
for arg in args
if match: arg.match MULTI_FLAG
result.push '-' + l for l in match[1].split ''
else
result.push arg
result