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

77 lines
1.8 KiB
Ruby
Raw Normal View History

2018-12-05 23:21:45 +05:30
# frozen_string_literal: true
2016-08-24 12:49:21 +05:30
class BranchesFinder
2018-03-27 19:54:05 +05:30
def initialize(repository, params = {})
2016-08-24 12:49:21 +05:30
@repository = repository
@params = params
end
def execute
2018-12-13 13:39:08 +05:30
branches = repository.branches_sorted_by(sort)
branches = by_search(branches)
2019-12-16 22:33:55 +05:30
branches = by_names(branches)
2018-12-13 13:39:08 +05:30
branches
2016-08-24 12:49:21 +05:30
end
private
attr_reader :repository, :params
2019-12-16 22:33:55 +05:30
def names
@params[:names].presence
end
2016-08-24 12:49:21 +05:30
def search
@params[:search].presence
end
def sort
@params[:sort].presence || 'name'
end
2018-12-13 13:39:08 +05:30
def by_search(branches)
return branches unless search
case search
when ->(v) { v.starts_with?('^') }
filter_branches_with_prefix(branches, search.slice(1..-1).upcase)
when ->(v) { v.ends_with?('$') }
filter_branches_with_suffix(branches, search.chop.upcase)
2016-08-24 12:49:21 +05:30
else
2018-12-13 13:39:08 +05:30
matches = filter_branches_by_name(branches, search.upcase)
set_exact_match_as_first_result(matches, search)
2016-08-24 12:49:21 +05:30
end
end
2018-12-13 13:39:08 +05:30
def filter_branches_with_prefix(branches, prefix)
branches.select { |branch| branch.name.upcase.starts_with?(prefix) }
end
def filter_branches_with_suffix(branches, suffix)
branches.select { |branch| branch.name.upcase.ends_with?(suffix) }
end
def filter_branches_by_name(branches, term)
branches.select { |branch| branch.name.upcase.include?(term) }
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 { |branch| branch.name.casecmp(term) == 0 }
end
2019-12-16 22:33:55 +05:30
def by_names(branches)
return branches unless names
branch_names = names.to_set
branches.select do |branch|
branch_names.include?(branch.name)
end
end
2016-08-24 12:49:21 +05:30
end