BigW Consortium Gitlab

search_results.rb 2.32 KB
Newer Older
1 2
module Gitlab
  class SearchResults
3
    attr_reader :current_user, :query
4

5
    # Limit search results by passed projects
6
    # It allows us to search only for projects user has access to
7
    attr_reader :limit_projects
8

9 10
    def initialize(current_user, limit_projects, query)
      @current_user = current_user
11
      @limit_projects = limit_projects || Project.all
12 13 14
      @query = Shellwords.shellescape(query) if query.present?
    end

Dmitriy Zaporozhets committed
15
    def objects(scope, page = nil)
16 17 18 19 20 21 22
      case scope
      when 'projects'
        projects.page(page).per(per_page)
      when 'issues'
        issues.page(page).per(per_page)
      when 'merge_requests'
        merge_requests.page(page).per(per_page)
23 24
      when 'milestones'
        milestones.page(page).per(per_page)
25 26 27 28 29 30
      else
        Kaminari.paginate_array([]).page(page).per(per_page)
      end
    end

    def total_count
31 32
      @total_count ||= projects_count + issues_count + merge_requests_count +
        milestones_count
33 34 35 36 37 38 39 40 41 42 43 44 45 46
    end

    def projects_count
      @projects_count ||= projects.count
    end

    def issues_count
      @issues_count ||= issues.count
    end

    def merge_requests_count
      @merge_requests_count ||= merge_requests.count
    end

47 48 49 50
    def milestones_count
      @milestones_count ||= milestones.count
    end

51 52 53 54 55 56 57
    def empty?
      total_count.zero?
    end

    private

    def projects
58
      limit_projects.search(query)
59 60 61
    end

    def issues
62
      issues = Issue.visible_to_user(current_user).where(project_id: project_ids_relation)
63

64 65 66 67 68
      if query =~ /#(\d+)\z/
        issues = issues.where(iid: $1)
      else
        issues = issues.full_search(query)
      end
69

70
      issues.order('updated_at DESC')
71 72
    end

73
    def milestones
74
      milestones = Milestone.where(project_id: project_ids_relation)
75 76 77 78
      milestones = milestones.search(query)
      milestones.order('updated_at DESC')
    end

79
    def merge_requests
80
      merge_requests = MergeRequest.in_projects(project_ids_relation)
81 82 83 84 85 86
      if query =~ /[#!](\d+)\z/
        merge_requests = merge_requests.where(iid: $1)
      else
        merge_requests = merge_requests.full_search(query)
      end
      merge_requests.order('updated_at DESC')
87 88 89 90 91 92 93 94 95
    end

    def default_scope
      'projects'
    end

    def per_page
      20
    end
96 97

    def project_ids_relation
98
      limit_projects.select(:id).reorder(nil)
99
    end
100 101
  end
end