1 // Generated by CoffeeScript 1.8.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, matchedRule, options, originalArgs, pos, rule, seenNonOptionArg, skippingArgument, value, _i, _j, _len, _len1, _ref;
18 skippingArgument = false;
20 args = normalizeArguments(args);
21 for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) {
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 (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
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 letPart, lines, rule, spaces, _i, _len, _ref;
65 lines.unshift("" + this.banner + "\n");
68 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
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 tuple, _i, _len, _results;
93 for (_i = 0, _len = rules.length; _i < _len; _i++) {
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, l, match, result, _i, _j, _len, _len1, _ref;
122 args = args.slice(0);
124 for (_i = 0, _len = args.length; _i < _len; _i++) {
126 if (match = arg.match(MULTI_FLAG)) {
127 _ref = match[1].split('');
128 for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
130 result.push('-' + l);