2019-11-05 07:06:20 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class GitRefsFinder
|
|
|
|
def initialize(repository, params = {})
|
|
|
|
@repository = repository
|
|
|
|
@params = params
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
attr_reader :repository, :params
|
|
|
|
|
|
|
|
def search
|
2022-02-03 19:13:53 -05:00
|
|
|
@params[:search].to_s.presence
|
2019-11-05 07:06:20 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def sort
|
2022-02-03 19:13:53 -05:00
|
|
|
@params[:sort].to_s.presence || 'name'
|
2019-11-05 07:06:20 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def by_search(refs)
|
|
|
|
return refs unless search
|
|
|
|
|
|
|
|
case search
|
|
|
|
when ->(v) { v.starts_with?('^') }
|
|
|
|
filter_refs_with_prefix(refs, search.slice(1..-1))
|
|
|
|
when ->(v) { v.ends_with?('$') }
|
|
|
|
filter_refs_with_suffix(refs, search.chop)
|
|
|
|
else
|
|
|
|
matches = filter_refs_by_name(refs, search)
|
|
|
|
set_exact_match_as_first_result(matches, search)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def filter_refs_with_prefix(refs, prefix)
|
2021-04-01 08:08:56 -04:00
|
|
|
prefix = prefix.downcase
|
|
|
|
|
|
|
|
refs.select { |ref| ref.name.downcase.starts_with?(prefix) }
|
2019-11-05 07:06:20 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def filter_refs_with_suffix(refs, suffix)
|
2021-04-01 08:08:56 -04:00
|
|
|
suffix = suffix.downcase
|
|
|
|
|
|
|
|
refs.select { |ref| ref.name.downcase.ends_with?(suffix) }
|
2019-11-05 07:06:20 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def filter_refs_by_name(refs, term)
|
2021-04-01 08:08:56 -04:00
|
|
|
term = term.downcase
|
|
|
|
|
|
|
|
refs.select { |ref| ref.name.downcase.include?(term) }
|
2019-11-05 07:06:20 -05:00
|
|
|
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
|
|
|
|
end
|