summaryrefslogtreecommitdiff
path: root/lib/gitlab/search/parsed_query.rb
blob: a397ce935cb5c7e7c9265387189a918e7d82d0c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# frozen_string_literal: true

module Gitlab
  module Search
    class ParsedQuery
      include Gitlab::Utils::StrongMemoize

      attr_reader :term, :filters

      def initialize(term, filters)
        @term = term
        @filters = filters
      end

      def filter_results(results)
        with_matcher = ->(filter) { filter[:matcher].present? }

        excluding = excluding_filters.select(&with_matcher)
        including = including_filters.select(&with_matcher)

        return unless excluding.any? || including.any?

        results.select! do |result|
          including.all? { |filter| filter[:matcher].call(filter, result) }
        end

        results.reject! do |result|
          excluding.any? { |filter| filter[:matcher].call(filter, result) }
        end

        results
      end

      private

      def including_filters
        processed_filters(:including)
      end

      def excluding_filters
        processed_filters(:excluding)
      end

      def processed_filters(type)
        excluding, including = strong_memoize(:processed_filters) do
          filters.partition { |filter| filter[:negated] }
        end

        case type
        when :including then including
        when :excluding then excluding
        else
          raise ArgumentError, type
        end
      end
    end
  end
end

Gitlab::Search::ParsedQuery.prepend_mod_with('Gitlab::Search::ParsedQuery')