UNPKG

2.28 kBtext/coffeescriptView Raw
1_ = require('lodash')
2_.str = require('underscore.string')
3parse = require('./parse')
4settings = require('./settings')
5state = require('./state')
6Option = require('./option')
7Signature = require('./signature')
8utils = require('./utils')
9
10module.exports = class Command
11 constructor: (options = {}) ->
12
13 if options.signature not instanceof Signature
14 throw new Error('Missing or invalid command signature')
15
16 if not _.isFunction(options.action)
17 throw new Error('Missing or invalid command action')
18
19 if options.options? and not _.isArray(options.options)
20 throw new Error('Invalid options')
21
22 @options = []
23
24 _.each(options.options, @option, this)
25 _.extend(this, _.omit(options, 'options'))
26
27 applyPermissions: (callback) ->
28 return callback() if not @permission?
29
30 permissionFunction = state.permissions[@permission]
31
32 if not permissionFunction?
33 error = new Error("Permission not found: #{@permission}")
34 return callback(error)
35
36 permissionFunction.call(this, callback)
37
38 # TODO: Tested implicitly by execute() tests, but it might
39 # worth to test this explicitly to find other corner cases
40 _parseOptions: (options) ->
41 allOptions = _.union(state.globalOptions, @options)
42 parsedOptions = parse.parseOptions(allOptions, options)
43
44 _checkElevation: (callback) ->
45 if @root?
46 utils.isElevated(callback)
47 else
48 return callback(null, true)
49
50 execute: (args = {}, callback) ->
51
52 @signature.compileParameters args.command, (error, params) =>
53 return callback?(error) if error?
54
55 @_checkElevation (error, isElevated) =>
56 return callback?(error) if error?
57
58 if @root and not isElevated
59 error = new Error('You need admin privileges to run this command')
60 error.code = 'EACCES'
61 return callback(error)
62
63 parsedOptions = @_parseOptions(args.options)
64
65 @applyPermissions (error) =>
66 return callback?(error) if error?
67
68 try
69 @action(params, parsedOptions, callback)
70 catch error
71 return callback?(error)
72
73 # Means the user is not declaring the callback
74 return callback?() if @action.length < 3
75
76 option: (option) ->
77 if option not instanceof Option
78 throw new Error('Invalid option')
79
80 return if _.find(@options, option)?
81 @options.push(option)
82
83 isWildcard: ->
84 return @signature.isWildcard()