environments_finder.rb 1.3 KB
Newer Older
D
Douwe Maan 已提交
1 2 3 4 5 6 7
class EnvironmentsFinder
  attr_reader :project, :current_user, :params

  def initialize(project, current_user, params = {})
    @project, @current_user, @params = project, current_user, params
  end

8
  def execute
D
Douwe Maan 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
    deployments = project.deployments
    deployments =
      if ref
        deployments_query = params[:with_tags] ? 'ref = :ref OR tag IS TRUE' : 'ref = :ref'
        deployments.where(deployments_query, ref: ref.to_s)
      elsif commit
        deployments.where(sha: commit.sha)
      else
        deployments.none
      end

    environment_ids = deployments
      .group(:environment_id)
      .select(:environment_id)

    environments = project.environments.available
      .where(id: environment_ids).order_by_last_deployed_at.to_a

27 28 29 30
    environments.select! do |environment|
      Ability.allowed?(current_user, :read_environment, environment)
    end

D
Douwe Maan 已提交
31 32 33 34 35 36 37 38 39 40 41 42
    if ref && commit
      environments.select! do |environment|
        environment.includes_commit?(commit)
      end
    end

    if ref && params[:recently_updated]
      environments.select! do |environment|
        environment.recently_updated_on_branch?(ref)
      end
    end

43
    environments
D
Douwe Maan 已提交
44 45 46 47 48 49 50 51 52 53 54 55
  end

  private

  def ref
    params[:ref].try(:to_s)
  end

  def commit
    params[:commit]
  end
end