UNPKG

1.56 kBtext/coffeescriptView Raw
1_ = require('lodash')
2_.str = require('underscore.string')
3parse = require('./parse')
4Signature = require('./signature')
5
6isValidAlias = (alias) ->
7 return _.isString(alias) or _.isArray(alias)
8
9module.exports = class Option
10 constructor: (options = {}) ->
11
12 if options.signature not instanceof Signature
13 throw new Error('Missing or invalid option signature')
14
15 if options.signature.hasParameters()
16 throw new Error('Use the parameter option attribute')
17
18 if options.alias? and not isValidAlias(options.alias)
19 throw new Error('Invalid alias')
20
21 if options.parameter? and not _.isString(options.parameter)
22 throw new Error('Invalid parameter')
23
24 if options.boolean and options.parameter?
25 throw new Error('Boolean options can\'t have parameters')
26
27 if not options.boolean and not options.parameter?
28 throw new Error('Missing parameter')
29
30 _.defaults options,
31 boolean: false
32 alias: []
33
34 _.extend(this, options)
35
36 getOptionsValue: (options) ->
37 value = options[@signature]
38
39 if not value?
40 value = _.chain(options)
41 .pick(@alias)
42 .values()
43 .first()
44 .value()
45
46 return value
47
48 matches: (value) ->
49 return false if not value?
50 return not _.any [
51 @boolean and not _.isBoolean(value)
52 not @boolean and _.isBoolean(value)
53 ]
54
55 toString: ->
56 signatures = _.map [ @signature.toString() ].concat(@alias), (signature) ->
57 return "-#{signature}" if signature.length <= 1
58 return "--#{signature}"
59
60 result = _.str.toSentence(signatures, ', ', ', ')
61 result += " <#{@parameter}>" if @parameter?
62 return result