summaryrefslogtreecommitdiff
path: root/lib/gitlab/chat_commands/deploy.rb
blob: 6bb854dc080b0b16210038f862c4071ec984ddad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module Gitlab
  module ChatCommands
    class Deploy < BaseCommand
      include Gitlab::Routing.url_helpers

      def self.match(text)
        /\Adeploy\s+(?<from>\S+.*)\s+to+\s+(?<to>\S+.*)\z/.match(text)
      end

      def self.help_message
        'deploy <environment> to <target-environment>'
      end

      def self.available?(project)
        project.builds_enabled?
      end

      def self.allowed?(project, user)
        can?(user, :create_deployment, project)
      end

      def execute(match)
        from = match[:from]
        to = match[:to]

        actions = find_actions(from, to)
        return unless actions.present?

        if actions.one?
          play!(from, to, actions.first)
        else
          Result.new(:error, 'Too many actions defined')
        end
      end

      private

      def play!(from, to, action)
        new_action = action.play(current_user)

        Result.new(:success, "Deployment from #{from} to #{to} started. Follow the progress: #{url(new_action)}.")
      end

      def find_actions(from, to)
        environment = project.environments.find_by(name: from)
        return unless environment

        environment.actions_for(to).select(&:starts_environment?)
      end

      def url(subject)
        polymorphic_url(
          [ subject.project.namespace.becomes(Namespace), subject.project, subject ])
      end
    end
  end
end