summaryrefslogtreecommitdiff
path: root/app/services/deployments/after_create_service.rb
blob: e0a4e5419cc71e66a2990627c9781f83aac989b3 (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
58
59
60
61
62
63
64
65
66
67
68
69
# frozen_string_literal: true

module Deployments
  class AfterCreateService
    attr_reader :deployment
    attr_reader :deployable

    delegate :environment, to: :deployment
    delegate :variables, to: :deployable
    delegate :options, to: :deployable, allow_nil: true

    def initialize(deployment)
      @deployment = deployment
      @deployable = deployment.deployable
    end

    def execute
      deployment.create_ref
      deployment.invalidate_cache

      update_environment(deployment)

      deployment
    end

    def update_environment(deployment)
      ActiveRecord::Base.transaction do
        if (url = expanded_environment_url)
          environment.external_url = url
        end

        environment.fire_state_event(action)

        if environment.save && !environment.stopped?
          deployment.update_merge_request_metrics!
          link_merge_requests(deployment)
        end
      end
    end

    private

    def link_merge_requests(deployment)
      unless Feature.enabled?(:deployment_merge_requests, deployment.project)
        return
      end

      LinkMergeRequestsService.new(deployment).execute
    end

    def environment_options
      options&.dig(:environment) || {}
    end

    def expanded_environment_url
      ExpandVariables.expand(environment_url, -> { variables }) if environment_url
    end

    def environment_url
      environment_options[:url]
    end

    def action
      environment_options[:action] || 'start'
    end
  end
end

Deployments::AfterCreateService.prepend_if_ee('EE::Deployments::AfterCreateService')