BigW Consortium Gitlab

environment.rb 2.07 KB
Newer Older
1
class Environment < ActiveRecord::Base
2
  belongs_to :project, required: true, validate: true
3 4 5

  has_many :deployments

Z.J. van de Weg committed
6
  before_validation :nullify_external_url
7
  before_save :set_environment_type
Z.J. van de Weg committed
8

9 10
  validates :name,
            presence: true,
11
            uniqueness: { scope: :project_id },
12 13 14
            length: { within: 0..255 },
            format: { with: Gitlab::Regex.environment_name_regex,
                      message: Gitlab::Regex.environment_name_regex_message }
15

16 17
  validates :external_url,
            uniqueness: { scope: :project_id },
Z.J. van de Weg committed
18 19 20
            length: { maximum: 255 },
            allow_nil: true,
            addressable_url: true
21

22
  delegate :stop_action, to: :last_deployment, allow_nil: true
23

24 25 26
  scope :available, -> { with_state(:available) }
  scope :stopped, -> { with_state(:stopped) }

27 28 29
  state_machine :state, initial: :available do
    event :start do
      transition stopped: :available
30 31
    end

32 33
    event :stop do
      transition available: :stopped
34 35
    end

36 37
    state :available
    state :stopped
38 39
  end

40 41 42
  def last_deployment
    deployments.last
  end
Z.J. van de Weg committed
43 44 45 46

  def nullify_external_url
    self.external_url = nil if self.external_url.blank?
  end
47

48 49 50 51 52 53 54 55 56 57 58
  def set_environment_type
    names = name.split('/')

    self.environment_type =
      if names.many?
        names.first
      else
        nil
      end
  end

59
  def includes_commit?(commit)
Z.J. van de Weg committed
60
    return false unless last_deployment
61

62
    last_deployment.includes_commit?(commit)
63
  end
64 65 66 67

  def update_merge_request_metrics?
    self.name == "production"
  end
68

69
  def first_deployment_for(commit)
70 71 72 73
    ref = project.repository.ref_name_for_sha(ref_path, commit.sha)

    return nil unless ref

74 75
    deployment_iid = ref.split('/').last
    deployments.find_by(iid: deployment_iid)
76 77
  end

78
  def ref_path
79
    "refs/environments/#{Shellwords.shellescape(name)}"
80
  end
81 82 83 84 85 86

  def formatted_external_url
    return nil unless external_url

    external_url.gsub(/\A.*?:\/\//, '')
  end
87 88 89 90

  def stoppable?
    available? && stop_action.present?
  end
91 92 93 94 95 96

  def stop!(current_user)
    return unless stoppable?

    stop_action.play(current_user)
  end
97
end