1 | _ = require('lodash')
|
2 | _.str = require('underscore.string')
|
3 | minimist = require('minimist')
|
4 | settings = require('./settings')
|
5 | state = require('./state')
|
6 | Parameter = require('./parameter')
|
7 |
|
8 | exports.normalizeInput = (argv) ->
|
9 | if argv is process.argv
|
10 | argv = argv.slice(2)
|
11 |
|
12 | return argv if _.isArray(argv)
|
13 |
|
14 | if _.isString(argv)
|
15 | return exports.split(argv)
|
16 |
|
17 | throw new Error('Invalid argument list')
|
18 |
|
19 | exports.parse = (argv) ->
|
20 | argv = exports.normalizeInput(argv)
|
21 | output = minimist(argv)
|
22 |
|
23 | options = _.omit(output, '_')
|
24 |
|
25 | result = {}
|
26 |
|
27 | result.options = options
|
28 | result.global = exports.parseOptions(state.globalOptions, options)
|
29 |
|
30 | if not _.isEmpty(output._)
|
31 | output._ = _.map output._, (word) ->
|
32 | wordParameter = new Parameter(word)
|
33 | return wordParameter.toString()
|
34 |
|
35 | result.command = output._.join(' ')
|
36 |
|
37 | return result
|
38 |
|
39 | exports.split = (string) ->
|
40 | return [] if not string?
|
41 |
|
42 |
|
43 | regex = ''
|
44 |
|
45 | pair = ([ start, end ]) ->
|
46 | start = '\\' + start
|
47 | end = '\\' + end
|
48 | regex += "#{start}[^#{end}]+#{end}|"
|
49 |
|
50 | pair('[]')
|
51 | pair('<>')
|
52 | pair('""')
|
53 | pair("''")
|
54 |
|
55 | regex += '\\S+'
|
56 |
|
57 | result = string.match(new RegExp(regex, 'g')) or []
|
58 |
|
59 | return _.map result, (word) ->
|
60 | word = _.str.unquote(word, '\'')
|
61 | word = _.str.unquote(word, '"')
|
62 | return word
|
63 |
|
64 | exports.parseOptions = (definedOptions, options = {}) ->
|
65 | result = {}
|
66 |
|
67 | for definedOption in definedOptions
|
68 | signature = definedOption.signature
|
69 |
|
70 | value = definedOption.getOptionsValue(options)
|
71 |
|
72 | if definedOption.required? and not value?
|
73 | if _.isString(definedOption.required)
|
74 | throw new Error(definedOption.required)
|
75 | else if definedOption.required
|
76 | throw new Error("Option #{definedOption.signature} is required")
|
77 |
|
78 | continue if not definedOption.matches(value)
|
79 |
|
80 | if /^\d+$/.test(value)
|
81 | value = _.parseInt(value)
|
82 |
|
83 | result[signature] = value
|
84 |
|
85 | return result
|