1 // Generated by CoffeeScript 1.10.0
3 var LONG_FLAG, MULTI_FLAG, OPTIONAL, OptionParser, SHORT_FLAG, buildRule, buildRules, normalizeArguments, repeat;
5 repeat = require('./helpers').repeat;
7 exports.OptionParser = OptionParser = (function() {
8 function OptionParser(rules, banner) {
10 this.rules = buildRules(rules);
13 OptionParser.prototype.parse = function(args) {
14 var arg, i, isOption, j, k, len, len1, matchedRule, options, originalArgs, pos, ref, rule, seenNonOptionArg, skippingArgument, value;
18 skippingArgument = false;
20 args = normalizeArguments(args);
21 for (i = j = 0, len = args.length; j < len; i = ++j) {
23 if (skippingArgument) {
24 skippingArgument = false;
28 pos = originalArgs.indexOf('--');
29 options["arguments"] = options["arguments"].concat(originalArgs.slice(pos + 1));
32 isOption = !!(arg.match(LONG_FLAG) || arg.match(SHORT_FLAG));
33 seenNonOptionArg = options["arguments"].length > 0;
34 if (!seenNonOptionArg) {
37 for (k = 0, len1 = ref.length; k < len1; k++) {
39 if (rule.shortFlag === arg || rule.longFlag === arg) {
41 if (rule.hasArgument) {
42 skippingArgument = true;
45 options[rule.name] = rule.isList ? (options[rule.name] || []).concat(value) : value;
50 if (isOption && !matchedRule) {
51 throw new Error("unrecognized option: " + arg);
54 if (seenNonOptionArg || !isOption) {
55 options["arguments"].push(arg);
61 OptionParser.prototype.help = function() {
62 var j, len, letPart, lines, ref, rule, spaces;
65 lines.unshift(this.banner + "\n");
68 for (j = 0, len = ref.length; j < len; j++) {
70 spaces = 15 - rule.longFlag.length;
71 spaces = spaces > 0 ? repeat(' ', spaces) : '';
72 letPart = rule.shortFlag ? rule.shortFlag + ', ' : ' ';
73 lines.push(' ' + letPart + rule.longFlag + spaces + rule.description);
75 return "\n" + (lines.join('\n')) + "\n";
82 LONG_FLAG = /^(--\w[\w\-]*)/;
84 SHORT_FLAG = /^(-\w)$/;
86 MULTI_FLAG = /^-(\w{2,})/;
88 OPTIONAL = /\[(\w+(\*?))\]/;
90 buildRules = function(rules) {
91 var j, len, results, tuple;
93 for (j = 0, len = rules.length; j < len; j++) {
95 if (tuple.length < 3) {
98 results.push(buildRule.apply(null, tuple));
103 buildRule = function(shortFlag, longFlag, description, options) {
105 if (options == null) {
108 match = longFlag.match(OPTIONAL);
109 longFlag = longFlag.match(LONG_FLAG)[1];
111 name: longFlag.substr(2),
112 shortFlag: shortFlag,
114 description: description,
115 hasArgument: !!(match && match[1]),
116 isList: !!(match && match[2])
120 normalizeArguments = function(args) {
121 var arg, j, k, l, len, len1, match, ref, result;
122 args = args.slice(0);
124 for (j = 0, len = args.length; j < len; j++) {
126 if (match = arg.match(MULTI_FLAG)) {
127 ref = match[1].split('');
128 for (k = 0, len1 = ref.length; k < len1; k++) {
130 result.push('-' + l);