BigW Consortium Gitlab

pipelines_finder.rb 2.21 KB
Newer Older
1
class PipelinesFinder
2
  attr_reader :project, :pipelines, :params
3

4 5
  ALLOWED_INDEXED_COLUMNS = %w[id status ref user_id].freeze

6
  def initialize(project, params = {})
7
    @project = project
8
    @pipelines = project.pipelines
9
    @params = params
10 11
  end

12 13 14 15 16
  def execute
    items = pipelines
    items = by_scope(items)
    items = by_status(items)
    items = by_ref(items)
17
    items = by_name(items)
Shinya Maeda committed
18 19
    items = by_username(items)
    items = by_yaml_errors(items)
20
    sort_items(items)
21 22 23 24
  end

  private

25
  def ids_for_ref(refs)
26 27 28
    pipelines.where(ref: refs).group(:ref).select('max(id)')
  end

29
  def from_ids(ids)
30 31 32 33
    pipelines.unscoped.where(id: ids)
  end

  def branches
34
    project.repository.branch_names
35 36 37
  end

  def tags
38
    project.repository.tag_names
39
  end
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

  def by_scope(items)
    case params[:scope]
    when 'running'
      items.running
    when 'pending'
      items.pending
    when 'finished'
      items.finished
    when 'branches'
      from_ids(ids_for_ref(branches))
    when 'tags'
      from_ids(ids_for_ref(tags))
    else
      items
    end
  end

  def by_status(items)
59 60 61
    return items unless HasStatus::AVAILABLE_STATUSES.include?(params[:status])

    items.where(status: params[:status])
62 63 64 65 66 67 68 69 70 71
  end

  def by_ref(items)
    if params[:ref].present?
      items.where(ref: params[:ref])
    else
      items
    end
  end

Shinya Maeda committed
72 73
  def by_name(items)
    if params[:name].present?
74
      items.joins(:user).where(users: { name: params[:name] })
Shinya Maeda committed
75 76 77 78 79
    else
      items
    end
  end

Shinya Maeda committed
80 81
  def by_username(items)
    if params[:username].present?
82
      items.joins(:user).where(users: { username: params[:username] })
83 84 85 86
    else
      items
    end
  end
87

Shinya Maeda committed
88
  def by_yaml_errors(items)
Shinya Maeda committed
89 90 91 92 93
    case Gitlab::Utils.to_boolean(params[:yaml_errors])
    when true
      items.where("yaml_errors IS NOT NULL")
    when false
      items.where("yaml_errors IS NULL")
94 95 96 97 98
    else
      items
    end
  end

99
  def sort_items(items)
100
    order_by = if ALLOWED_INDEXED_COLUMNS.include?(params[:order_by])
101 102 103 104
                 params[:order_by]
               else
                 :id
               end
105

106 107 108 109 110
    sort = if params[:sort] =~ /\A(ASC|DESC)\z/i
             params[:sort]
           else
             :desc
           end
111

112
    items.order(order_by => sort)
113
  end
114
end