UNPKG

2.01 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 configuration:
23 'parse-numbers': false
24
25 options = _.omit(output, '_')
26
27 result = {}
28
29 result.options = _.mapValues options, (value) ->
30 if /^[\d\.]+$/.test(value)
31 return parseFloat(value)
32 return value
33
34 result.global = exports.parseOptions(state.globalOptions, options)
35
36 if not _.isEmpty(output._)
37 output._ = _.map output._, (word) ->
38 wordParameter = new Parameter(word)
39 return wordParameter.toString()
40
41 result.command = output._.join(' ')
42
43 return result
44
45exports.split = (string) ->
46 return [] if not string?
47
48 # TODO: Refactor this to use a manual lexer
49 regex = ''
50
51 pair = ([ start, end ]) ->
52 start = '\\' + start
53 end = '\\' + end
54 regex += "#{start}[^#{end}]+#{end}|"
55
56 pair('[]')
57 pair('<>')
58 pair('""')
59 pair("''")
60
61 regex += '\\S+'
62
63 result = string.match(new RegExp(regex, 'g')) or []
64
65 return _.map result, (word) ->
66 word = _.str.unquote(word, '\'')
67 word = _.str.unquote(word, '"')
68 return word
69
70exports.parseOptions = (definedOptions, options = {}) ->
71 result = {}
72
73 for definedOption in definedOptions
74 signature = definedOption.signature
75
76 value = definedOption.getOptionsValue(options)
77
78 if definedOption.required? and not value?
79 if _.isString(definedOption.required)
80 throw new Error(definedOption.required)
81 else if definedOption.required
82 throw new Error("Option #{definedOption.signature} is required")
83
84 continue if not definedOption.matches(value)
85
86 if /^\d+$/.test(value)
87 value = _.parseInt(value)
88
89 result[signature] = value
90
91 return result