ci_status.rb 1.97 KB
Newer Older
1 2 3 4
module CiStatus
  extend ActiveSupport::Concern

  module ClassMethods
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
    def status_sql
      builds = all.select('count(id)').to_sql
      success = all.success.select('count(id)').to_sql
      ignored = all.failed.where(allow_failure: true).select('count(id)').to_sql if all.try(:ignored)
      ignored ||= '0'
      pending = all.pending.select('count(id)').to_sql
      running = all.running.select('count(id)').to_sql
      canceled = all.canceled.select('count(id)').to_sql

      deduce_status = "(CASE
        WHEN (#{builds})=0 THEN 'skipped'
        WHEN (#{builds})=(#{success})+(#{ignored}) THEN 'success'
        WHEN (#{builds})=(#{pending}) THEN 'pending'
        WHEN (#{builds})=(#{canceled}) THEN 'canceled'
        WHEN (#{running})+(#{pending})>0 THEN 'running'
        ELSE 'failed'
      END)"

      deduce_status
    end

26
    def status
27
      pluck(self.status_sql).first
28 29 30 31 32 33 34 35 36
    end

    def duration
      duration_array = all.map(&:duration).compact
      duration_array.reduce(:+).to_i
    end
  end

  included do
Kamil Trzcinski's avatar
Kamil Trzcinski committed
37
    validates :status, inclusion: { in: %w(pending running failed success canceled skipped) }
38 39 40 41 42 43 44

    state_machine :status, initial: :pending do
      state :pending, value: 'pending'
      state :running, value: 'running'
      state :failed, value: 'failed'
      state :success, value: 'success'
      state :canceled, value: 'canceled'
Kamil Trzcinski's avatar
Kamil Trzcinski committed
45
      state :skipped, value: 'skipped'
46 47 48 49 50 51
    end

    scope :running, -> { where(status: 'running') }
    scope :pending, -> { where(status: 'pending') }
    scope :success, -> { where(status: 'success') }
    scope :failed, -> { where(status: 'failed')  }
52
    scope :canceled, -> { where(status: 'canceled')  }
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    scope :running_or_pending, -> { where(status: [:running, :pending]) }
    scope :finished, -> { where(status: [:success, :failed, :canceled]) }
  end

  def started?
    !pending? && !canceled? && started_at
  end

  def active?
    running? || pending?
  end

  def complete?
    canceled? || success? || failed?
  end
68
end