UNPKG

1.87 kBtext/coffeescriptView Raw
1_ = require('lodash')
2_.str = require('underscore.string')
3yargsParser = require('yargs-parser')
4settings = require('./settings')
5state = require('./state')
6Parameter = require('./parameter')
7
8exports.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
19exports.parse = (argv) ->
20 argv = exports.normalizeInput(argv)
21 output = yargsParser(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
39exports.split = (string) ->
40 return [] if not string?
41
42 # TODO: Refactor this to use a manual lexer
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
64exports.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