BigW Consortium Gitlab

command_definition.rb 2.14 KB
Newer Older
1
module Gitlab
2
  module QuickActions
3
    class CommandDefinition
4 5
      attr_accessor :name, :aliases, :description, :explanation, :params,
        :condition_block, :parse_params_block, :action_block
6

7
      def initialize(name, attributes = {})
8
        @name = name
9

10 11 12 13
        @aliases = attributes[:aliases] || []
        @description = attributes[:description] || ''
        @explanation = attributes[:explanation] || ''
        @params = attributes[:params] || []
Douwe Maan committed
14
        @condition_block = attributes[:condition_block]
15 16
        @parse_params_block = attributes[:parse_params_block]
        @action_block = attributes[:action_block]
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
      end

      def all_names
        [name, *aliases]
      end

      def noop?
        action_block.nil?
      end

      def available?(opts)
        return true unless condition_block

        context = OpenStruct.new(opts)
        context.instance_exec(&condition_block)
      end

34 35 36 37 38 39 40 41 42 43
      def explain(context, opts, arg)
        return unless available?(opts)

        if explanation.respond_to?(:call)
          execute_block(explanation, context, arg)
        else
          explanation
        end
      end

44
      def execute(context, opts, arg)
45 46
        return if noop? || !available?(opts)

47
        execute_block(action_block, context, arg)
48 49 50
      end

      def to_h(opts)
51 52
        context = OpenStruct.new(opts)

53 54 55 56 57
        desc = description
        if desc.respond_to?(:call)
          desc = context.instance_exec(&desc) rescue ''
        end

58 59 60 61 62
        prms = params
        if prms.respond_to?(:call)
          prms = Array(context.instance_exec(&prms)) rescue params
        end

63 64 65 66
        {
          name: name,
          aliases: aliases,
          description: desc,
67
          params: prms
68 69
        }
      end
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

      private

      def execute_block(block, context, arg)
        if arg.present?
          parsed = parse_params(arg, context)
          context.instance_exec(parsed, &block)
        elsif block.arity == 0
          context.instance_exec(&block)
        end
      end

      def parse_params(arg, context)
        return arg unless parse_params_block

        context.instance_exec(arg, &parse_params_block)
      end
87 88 89
    end
  end
end