debian-mirror-gitlab/app/finders/git_refs_finder.rb

63 lines
1.4 KiB
Ruby
Raw Normal View History

2019-12-26 22:10:19 +05:30
# frozen_string_literal: true
class GitRefsFinder
def initialize(repository, params = {})
@repository = repository
@params = params
end
protected
attr_reader :repository, :params
def search
@params[:search].presence
end
def sort
@params[:sort].presence || 'name'
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-29 21:17:54 +05:30
prefix = prefix.downcase
refs.select { |ref| ref.name.downcase.starts_with?(prefix) }
2019-12-26 22:10:19 +05:30
end
def filter_refs_with_suffix(refs, suffix)
2021-04-29 21:17:54 +05:30
suffix = suffix.downcase
refs.select { |ref| ref.name.downcase.ends_with?(suffix) }
2019-12-26 22:10:19 +05:30
end
def filter_refs_by_name(refs, term)
2021-04-29 21:17:54 +05:30
term = term.downcase
refs.select { |ref| ref.name.downcase.include?(term) }
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
end