2019-12-26 22:10:19 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class GitRefsFinder
|
2023-03-04 22:38:38 +05:30
|
|
|
include Gitlab::Utils::StrongMemoize
|
|
|
|
|
2019-12-26 22:10:19 +05:30
|
|
|
def initialize(repository, params = {})
|
|
|
|
@repository = repository
|
|
|
|
@params = params
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
attr_reader :repository, :params
|
|
|
|
|
|
|
|
def by_search(refs)
|
|
|
|
return refs unless search
|
|
|
|
|
2023-03-04 22:38:38 +05:30
|
|
|
matches = filter_refs(refs, search)
|
|
|
|
return matches if regex_search?
|
2021-04-29 21:17:54 +05:30
|
|
|
|
2023-03-04 22:38:38 +05:30
|
|
|
set_exact_match_as_first_result(matches, search)
|
2019-12-26 22:10:19 +05:30
|
|
|
end
|
|
|
|
|
2023-03-04 22:38:38 +05:30
|
|
|
def search
|
|
|
|
@params[:search].to_s.presence
|
2019-12-26 22:10:19 +05:30
|
|
|
end
|
2023-03-04 22:38:38 +05:30
|
|
|
strong_memoize_attr :search
|
2019-12-26 22:10:19 +05:30
|
|
|
|
2023-03-04 22:38:38 +05:30
|
|
|
def sort
|
|
|
|
@params[:sort].to_s.presence || 'name'
|
|
|
|
end
|
2021-04-29 21:17:54 +05:30
|
|
|
|
2023-03-04 22:38:38 +05:30
|
|
|
def filter_refs(refs, term)
|
|
|
|
regex_string = Regexp.quote(term.downcase)
|
|
|
|
regex_string = unescape_regex_operators(regex_string) if regex_search?
|
|
|
|
refs.select { |ref| /#{regex_string}/ === ref.name.downcase }
|
2019-12-26 22:10:19 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def set_exact_match_as_first_result(matches, term)
|
|
|
|
exact_match_index = find_exact_match_index(matches, term)
|
|
|
|
matches.insert(0, matches.delete_at(exact_match_index)) if exact_match_index
|
|
|
|
matches
|
|
|
|
end
|
|
|
|
|
|
|
|
def find_exact_match_index(matches, term)
|
|
|
|
matches.index { |ref| ref.name.casecmp(term) == 0 }
|
|
|
|
end
|
2023-03-04 22:38:38 +05:30
|
|
|
|
|
|
|
def regex_search?
|
|
|
|
Regexp.union('^', '$', '*') === search
|
|
|
|
end
|
2023-03-17 16:20:25 +05:30
|
|
|
strong_memoize_attr :regex_search?
|
2023-03-04 22:38:38 +05:30
|
|
|
|
|
|
|
def unescape_regex_operators(regex_string)
|
|
|
|
regex_string.sub('\^', '^').gsub('\*', '.*?').sub('\$', '$')
|
|
|
|
end
|
2019-12-26 22:10:19 +05:30
|
|
|
end
|