search_controller.rb 2.42 KB
Newer Older
1 2
# frozen_string_literal: true

3
class SearchController < ApplicationController
4
  include ControllerWithCrossProjectAccessCheck
5
  include SearchHelper
6
  include RendersCommits
7

8 9
  around_action :allow_gitaly_ref_name_caching

10 11 12 13 14 15
  skip_before_action :authenticate_user!
  requires_cross_project_access if: -> do
    search_term_present = params[:search].present? || params[:term].present?
    search_term_present && !params[:project_id].present?
  end

16
  layout 'search'
17

18
  def show
19 20
    @project = search_service.project
    @group = search_service.group
21

Valery Sizov's avatar
Valery Sizov committed
22
    return if params[:search].blank?
23

24 25
    @search_term = params[:search]

26 27 28 29
    @scope = search_service.scope
    @show_snippets = search_service.show_snippets?
    @search_results = search_service.search_results
    @search_objects = search_service.search_objects
30

31
    render_commits if @scope == 'commits'
32
    eager_load_user_status if @scope == 'users'
33

34 35
    increment_navbar_searches_counter

36
    check_single_commit_result
Izaak Alpert's avatar
Izaak Alpert committed
37
  end
38

39 40 41 42 43 44 45 46 47
  def count
    params.require([:search, :scope])

    scope = search_service.scope
    count = search_service.search_results.formatted_count(scope)

    render json: { count: count }
  end

48
  # rubocop: disable CodeReuse/ActiveRecord
49 50
  def autocomplete
    term = params[:term]
51 52 53 54 55 56

    if params[:project_id].present?
      @project = Project.find_by(id: params[:project_id])
      @project = nil unless can?(current_user, :read_project, @project)
    end

57 58 59 60
    @ref = params[:project_ref] if params[:project_ref].present?

    render json: search_autocomplete_opts(term).to_json
  end
61
  # rubocop: enable CodeReuse/ActiveRecord
62 63 64

  private

65 66 67 68
  def render_commits
    @search_objects = prepare_commits_for_rendering(@search_objects)
  end

69
  def eager_load_user_status
70 71
    return if Feature.disabled?(:users_search, default_enabled: true)

72 73 74
    @search_objects = @search_objects.eager_load(:status) # rubocop:disable CodeReuse/ActiveRecord
  end

75 76 77 78 79 80
  def check_single_commit_result
    if @search_results.single_commit_result?
      only_commit = @search_results.objects('commits').first
      query = params[:search].strip.downcase
      found_by_commit_sha = Commit.valid_hash?(query) && only_commit.sha.start_with?(query)

81
      redirect_to project_commit_path(@project, only_commit) if found_by_commit_sha
82 83
    end
  end
84 85 86 87 88 89

  def increment_navbar_searches_counter
    return if params[:nav_source] != 'navbar'

    Gitlab::UsageDataCounters::SearchCounter.increment_navbar_searches_count
  end
90
end