1 | var Option, Signature, _, isValidAlias, parse;
|
2 |
|
3 | _ = require('lodash');
|
4 |
|
5 | _.str = require('underscore.string');
|
6 |
|
7 | parse = require('./parse');
|
8 |
|
9 | Signature = require('./signature');
|
10 |
|
11 | isValidAlias = function(alias) {
|
12 | return _.isString(alias) || _.isArray(alias);
|
13 | };
|
14 |
|
15 | module.exports = Option = (function() {
|
16 | function Option(options) {
|
17 | if (options == null) {
|
18 | options = {};
|
19 | }
|
20 | if (!(options.signature instanceof Signature)) {
|
21 | throw new Error('Missing or invalid option signature');
|
22 | }
|
23 | if (options.signature.hasParameters()) {
|
24 | throw new Error('Use the parameter option attribute');
|
25 | }
|
26 | if ((options.alias != null) && !isValidAlias(options.alias)) {
|
27 | throw new Error('Invalid alias');
|
28 | }
|
29 | if ((options.parameter != null) && !_.isString(options.parameter)) {
|
30 | throw new Error('Invalid parameter');
|
31 | }
|
32 | if (options.boolean && (options.parameter != null)) {
|
33 | throw new Error('Boolean options can\'t have parameters');
|
34 | }
|
35 | if (!options.boolean && (options.parameter == null)) {
|
36 | throw new Error('Missing parameter');
|
37 | }
|
38 | _.defaults(options, {
|
39 | boolean: false,
|
40 | alias: []
|
41 | });
|
42 | _.extend(this, options);
|
43 | }
|
44 |
|
45 | Option.prototype.getOptionsValue = function(options) {
|
46 | var value;
|
47 | value = options[this.signature];
|
48 | if (value == null) {
|
49 | value = _.chain(options).pick(this.alias).values().first().value();
|
50 | }
|
51 | return value;
|
52 | };
|
53 |
|
54 | Option.prototype.matches = function(value) {
|
55 | if (value == null) {
|
56 | return false;
|
57 | }
|
58 | return !_.any([this.boolean && !_.isBoolean(value), !this.boolean && _.isBoolean(value)]);
|
59 | };
|
60 |
|
61 | Option.prototype.toString = function() {
|
62 | var result, signatures;
|
63 | signatures = _.map([this.signature.toString()].concat(this.alias), function(signature) {
|
64 | if (signature.length <= 1) {
|
65 | return "-" + signature;
|
66 | }
|
67 | return "--" + signature;
|
68 | });
|
69 | result = _.str.toSentence(signatures, ', ', ', ');
|
70 | if (this.parameter != null) {
|
71 | result += " <" + this.parameter + ">";
|
72 | }
|
73 | return result;
|
74 | };
|
75 |
|
76 | return Option;
|
77 |
|
78 | })();
|