1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | var util = require('util');
|
19 |
|
20 | var optparse = require('./extern/optparse/lib/optparse');
|
21 |
|
22 | var constants = require('./constants');
|
23 | var run = require('./run');
|
24 |
|
25 | var halt = function(parser) {
|
26 | parser.halt(parser);
|
27 | parser._halted = true;
|
28 | run.exitCode = 1;
|
29 | };
|
30 |
|
31 | var getParser = function(options) {
|
32 | var switches = [];
|
33 |
|
34 | switches = switches.concat(constants.DEFAULT_OPTIONS);
|
35 | switches = switches.concat(options);
|
36 | var parser = new optparse.OptionParser(switches);
|
37 | parser._options = options;
|
38 |
|
39 | parser.on('help', function() {
|
40 | util.puts(parser.toString());
|
41 | halt(parser);
|
42 | });
|
43 |
|
44 | parser.on('version', function() {
|
45 | util.puts(constants.VERSION);
|
46 | halt(parser);
|
47 | });
|
48 |
|
49 | parser.on(function(opt) {
|
50 | util.puts('No handler was defined for option: ' + opt);
|
51 | halt(parser);
|
52 | });
|
53 |
|
54 | parser.on('*', function(opt, value) {
|
55 | util.puts('wild handler for ' + opt + ', value=' + value);
|
56 | halt(parser);
|
57 | });
|
58 |
|
59 | return parser;
|
60 | };
|
61 |
|
62 | var getParserOptionsObject = function(options) {
|
63 | var i, option, split, optionName, optionType;
|
64 | var optionsLen = options.length;
|
65 | var optionsObj = {};
|
66 |
|
67 | for (i = 0; i < optionsLen; i++) {
|
68 | option = options[i][1];
|
69 | split = option.split(' ');
|
70 |
|
71 | optionName = split[0].replace(/\-\-/, '');
|
72 | if (split.length === 1) {
|
73 | optionType = 'boolean';
|
74 | }
|
75 | else {
|
76 | optionType = 'value';
|
77 | }
|
78 |
|
79 | optionsObj[optionName] = optionType;
|
80 | }
|
81 |
|
82 | return optionsObj;
|
83 | };
|
84 |
|
85 | var parseArgv = function(parser, argv) {
|
86 | var optionName, optionType;
|
87 | var optionsObj = getParserOptionsObject(parser._options);
|
88 | var options = {};
|
89 |
|
90 | function handleParserOption(optionName, optionType) {
|
91 | parser.on(optionName, function(opt, value) {
|
92 | if (optionType === 'boolean') {
|
93 | options[optionName] = true;
|
94 | }
|
95 | else if (optionType === 'value') {
|
96 | if (value) {
|
97 | options[optionName] = value;
|
98 | }
|
99 | }
|
100 | });
|
101 | }
|
102 |
|
103 | for (optionName in optionsObj) {
|
104 | if (optionsObj.hasOwnProperty(optionName)) {
|
105 | optionType = optionsObj[optionName];
|
106 | handleParserOption(optionName, optionType);
|
107 | }
|
108 | }
|
109 |
|
110 | parser.parse(argv);
|
111 | return options;
|
112 | };
|
113 |
|
114 | exports.getParser = getParser;
|
115 | exports.parseArgv = parseArgv;
|