debian-mirror-gitlab/lib/gitlab/search/query.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

84 lines
2.3 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
2018-11-08 19:23:39 +05:30
module Gitlab
module Search
class Query < SimpleDelegator
2019-02-15 15:39:39 +05:30
include EncodingHelper
2021-03-11 19:13:27 +05:30
QUOTES_REGEXP = %r{\A"|"\Z}.freeze
TOKEN_WITH_QUOTES_REGEXP = %r{\s(?=(?:[^"]|"[^"]*")*$)}.freeze
2018-11-08 19:23:39 +05:30
def initialize(query, filter_opts = {}, &block)
@raw_query = query.dup
@filters = []
@filter_options = { default_parser: :downcase.to_proc }.merge(filter_opts)
2022-08-27 11:52:29 +05:30
self.instance_eval(&block) if block
2018-11-08 19:23:39 +05:30
@query = Gitlab::Search::ParsedQuery.new(*extract_filters)
# set the ParsedQuery as our default delegator thanks to SimpleDelegator
super(@query)
end
private
def filter(name, **attributes)
2020-10-24 23:57:45 +05:30
filter = {
parser: @filter_options[:default_parser],
name: name
}.merge(attributes)
2018-11-08 19:23:39 +05:30
@filters << filter
end
def filter_options(**options)
@filter_options.merge!(options)
end
def extract_filters
fragments = []
2021-03-11 19:13:27 +05:30
query_tokens = parse_raw_query
2018-11-08 19:23:39 +05:30
filters = @filters.each_with_object([]) do |filter, parsed_filters|
2022-11-25 23:54:43 +05:30
matches = query_tokens.select { |part| part =~ /\A-?#{filter[:name]}:/ }
2021-03-11 19:13:27 +05:30
2022-11-25 23:54:43 +05:30
next unless matches.any?
2018-11-08 19:23:39 +05:30
2022-11-25 23:54:43 +05:30
matches.each do |match|
query_filter = filter.dup
2018-11-08 19:23:39 +05:30
2022-11-25 23:54:43 +05:30
input = match.split(':')[1..].join
2018-11-08 19:23:39 +05:30
2022-11-25 23:54:43 +05:30
next if input.empty?
query_filter[:negated] = match.start_with?("-")
query_filter[:value] = parse_filter(query_filter, input.gsub(QUOTES_REGEXP, ''))
query_filter[:regex_value] = Regexp.escape(query_filter[:value]).gsub('\*', '.*?')
fragments << match
parsed_filters << query_filter
end
2018-11-08 19:23:39 +05:30
end
2021-03-11 19:13:27 +05:30
query = (query_tokens - fragments).join(' ')
2021-02-22 17:27:13 +05:30
query = '*' if query.empty?
2018-11-08 19:23:39 +05:30
[query, filters]
end
def parse_filter(filter, input)
2019-02-15 15:39:39 +05:30
result = filter[:parser].call(input)
@filter_options[:encode_binary] ? encode_binary(result) : result
2018-11-08 19:23:39 +05:30
end
2021-03-11 19:13:27 +05:30
def parse_raw_query
# Positive lookahead for any non-quote char or even number of quotes
# for example '"search term" path:"foo bar.txt"' would break into
# ["search term", "path:\"foo bar.txt\""]
@raw_query.split(TOKEN_WITH_QUOTES_REGEXP).reject(&:empty?)
end
2018-11-08 19:23:39 +05:30
end
end
end