summaryrefslogtreecommitdiff
path: root/app/services/create_deployment_service.rb
blob: 47f9b2c621c06b24a3aa9c7f22cc672477cc78b6 (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
70
71
class CreateDeploymentService < BaseService
  def execute(deployable = nil)
    return unless executable?

    ActiveRecord::Base.transaction do
      @deployable = deployable

      @environment = environment
      @environment.external_url = expanded_url if expanded_url
      @environment.fire_state_event(action)

      return unless @environment.save
      return if @environment.stopped?

      deploy.tap do |deployment|
        deployment.update_merge_request_metrics!
      end
    end
  end

  private

  def executable?
    project && name.present?
  end

  def deploy
    project.deployments.create(
      environment: @environment,
      ref: params[:ref],
      tag: params[:tag],
      sha: params[:sha],
      user: current_user,
      deployable: @deployable,
      on_stop: options[:on_stop])
  end

  def environment
    @environment ||= project.environments.find_or_create_by(name: expanded_name)
  end

  def expanded_name
    ExpandVariables.expand(name, variables)
  end

  def expanded_url
    return unless url

    @expanded_url ||= ExpandVariables.expand(url, variables)
  end

  def name
    params[:environment]
  end

  def url
    options[:url]
  end

  def options
    params[:options] || {}
  end

  def variables
    params[:variables] || []
  end

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