1 | _ = require('lodash')
|
2 | _.str = require('underscore.string')
|
3 | parse = require('./parse')
|
4 |
|
5 | REGEX_REQUIRED = /^<(.*)>$/
|
6 | REGEX_OPTIONAL = /^\[(.*)\]$/
|
7 | REGEX_VARIADIC = /^[<\[](.*)[\.]{3}[>\]]$/
|
8 | REGEX_MULTIWORD = /\s/
|
9 | REGEX_STDIN = /^[<\[]\|(.*)[\]>]$/
|
10 | STDIN_CHARACTER = '|'
|
11 |
|
12 | module.exports = class Parameter
|
13 | constructor: (parameter) ->
|
14 |
|
15 | if _.isNumber(parameter)
|
16 | parameter = String(parameter)
|
17 |
|
18 | if not parameter? or not _.isString(parameter)
|
19 | throw new Error("Missing or invalid parameter: #{parameter}")
|
20 |
|
21 | @parameter = parameter
|
22 |
|
23 | if @isVariadic() and @allowsStdin()
|
24 | throw new Error('Parameter can\'t be variadic and allow stdin')
|
25 |
|
26 | _testRegex: (regex) ->
|
27 | return regex.test(@parameter)
|
28 |
|
29 | isRequired: ->
|
30 | return @_testRegex(REGEX_REQUIRED)
|
31 |
|
32 | isOptional: ->
|
33 | return @_testRegex(REGEX_OPTIONAL)
|
34 |
|
35 | isVariadic: ->
|
36 | return @_testRegex(REGEX_VARIADIC)
|
37 |
|
38 | isWord: ->
|
39 | return not _.any [
|
40 | @isRequired()
|
41 | @isOptional()
|
42 | ]
|
43 |
|
44 | isMultiWord: ->
|
45 | return @_testRegex(REGEX_MULTIWORD)
|
46 |
|
47 | allowsStdin: ->
|
48 | return @parameter[1] is STDIN_CHARACTER
|
49 |
|
50 | getValue: ->
|
51 | return @parameter if @isWord()
|
52 | regex = REGEX_REQUIRED if @isRequired()
|
53 | regex = REGEX_OPTIONAL if @isOptional()
|
54 | regex = REGEX_VARIADIC if @isVariadic()
|
55 | regex = REGEX_STDIN if @allowsStdin()
|
56 | result = @parameter.match(regex)
|
57 | return result[1]
|
58 |
|
59 | getType: ->
|
60 | return 'word' if @isWord()
|
61 | return 'parameter'
|
62 |
|
63 | matches: (parameter) ->
|
64 | return parameter is @parameter if @isWord()
|
65 | parameterWordsLength = parse.split(parameter).length
|
66 |
|
67 | if @isVariadic()
|
68 | return true if @isOptional()
|
69 | return false if parameterWordsLength < 1
|
70 | else
|
71 | if @isRequired()
|
72 | return false if parameterWordsLength < 1
|
73 |
|
74 | return true
|
75 |
|
76 | toString: ->
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | if @isMultiWord() and @isWord()
|
83 | return _.str.quote(@parameter)
|
84 |
|
85 | return @parameter
|