1 | _ = require('lodash')
|
2 | _.str = require('underscore.string')
|
3 | parse = require('./parse')
|
4 | settings = require('./settings')
|
5 | state = require('./state')
|
6 | Option = require('./option')
|
7 | Signature = require('./signature')
|
8 | utils = require('./utils')
|
9 |
|
10 | module.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 |
|
39 |
|
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 | try
|
64 | parsedOptions = @_parseOptions(args.options)
|
65 | catch error
|
66 | return callback?(error)
|
67 |
|
68 | @applyPermissions (error) =>
|
69 | return callback?(error) if error?
|
70 |
|
71 | try
|
72 | @action(params, parsedOptions, callback)
|
73 | catch error
|
74 | return callback?(error)
|
75 |
|
76 |
|
77 | return callback?() if @action.length < 3
|
78 |
|
79 | option: (option) ->
|
80 | if option not instanceof Option
|
81 | throw new Error('Invalid option')
|
82 |
|
83 | return if _.find(@options, option)?
|
84 | @options.push(option)
|
85 |
|
86 | isWildcard: ->
|
87 | return @signature.isWildcard()
|