2018-09-11 15:08:34 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-07-07 12:19:21 -04:00
|
|
|
class BranchesFinder
|
2017-11-15 09:56:36 -05:00
|
|
|
def initialize(repository, params = {})
|
2016-07-07 12:19:21 -04:00
|
|
|
@repository = repository
|
|
|
|
@params = params
|
|
|
|
end
|
|
|
|
|
|
|
|
def execute
|
2018-10-11 10:25:30 -04:00
|
|
|
branches = repository.branches_sorted_by(sort)
|
|
|
|
branches = by_search(branches)
|
2019-06-18 10:20:11 -04:00
|
|
|
branches = by_names(branches)
|
2018-10-11 10:25:30 -04:00
|
|
|
branches
|
2016-07-07 12:19:21 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
attr_reader :repository, :params
|
|
|
|
|
2019-06-18 10:20:11 -04:00
|
|
|
def names
|
|
|
|
@params[:names].presence
|
|
|
|
end
|
|
|
|
|
2016-07-07 12:19:21 -04:00
|
|
|
def search
|
|
|
|
@params[:search].presence
|
|
|
|
end
|
|
|
|
|
|
|
|
def sort
|
|
|
|
@params[:sort].presence || 'name'
|
|
|
|
end
|
|
|
|
|
2018-10-11 10:25:30 -04:00
|
|
|
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-07-07 12:19:21 -04:00
|
|
|
else
|
2018-10-11 10:25:30 -04:00
|
|
|
matches = filter_branches_by_name(branches, search.upcase)
|
|
|
|
set_exact_match_as_first_result(matches, search)
|
2016-07-07 12:19:21 -04:00
|
|
|
end
|
|
|
|
end
|
2018-10-11 10:25:30 -04:00
|
|
|
|
|
|
|
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-06-18 10:20:11 -04:00
|
|
|
|
|
|
|
def by_names(branches)
|
|
|
|
return branches unless names
|
|
|
|
|
|
|
|
branch_names = names.to_set
|
|
|
|
branches.filter do |branch|
|
|
|
|
branch_names.include?(branch.name)
|
|
|
|
end
|
|
|
|
end
|
2016-07-07 12:19:21 -04:00
|
|
|
end
|