diff --git a/lib/gitlab/git/finders/refs_finder.rb b/lib/gitlab/git/finders/refs_finder.rb new file mode 100644 index 0000000000000000000000000000000000000000..a0117bc0fa91e45c9f1b37f32415aff7506e2174 --- /dev/null +++ b/lib/gitlab/git/finders/refs_finder.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +module Gitlab + module Git + module Finders + class RefsFinder + attr_reader :repository, :search, :ref_type + + UnknownRefTypeError = Class.new(StandardError) + + def initialize(repository, search:, ref_type:) + @repository = repository + @search = search + @ref_type = ref_type + end + + def execute + pattern = [prefix, search, "*"].compact.join + + repository.list_refs( + [pattern] + ) + end + + private + + def prefix + case ref_type + when :branches + Gitlab::Git::BRANCH_REF_PREFIX + when :tags + Gitlab::Git::TAG_REF_PREFIX + else + raise UnknownRefTypeError, "ref_type must be one of [:branches, :tags]" + end + end + end + end + end +end diff --git a/spec/lib/gitlab/git/finders/refs_finder_spec.rb b/spec/lib/gitlab/git/finders/refs_finder_spec.rb new file mode 100644 index 0000000000000000000000000000000000000000..63d794d1e594cf0b7db8a6799430db48b52b3902 --- /dev/null +++ b/spec/lib/gitlab/git/finders/refs_finder_spec.rb @@ -0,0 +1,62 @@ +# frozen_string_literal: true + +require "spec_helper" + +RSpec.describe Gitlab::Git::Finders::RefsFinder, feature_category: :source_code_management do + let_it_be(:user) { create(:user) } + let_it_be(:project) { create(:project, :repository) } + + let(:repository) { project.repository } + let(:finder) { described_class.new(repository, **params) } + let(:params) { {} } + + describe "#execute" do + subject { finder.execute } + + context "when :ref_type is :branches" do + let(:params) do + { search: "mast", ref_type: :branches } + end + + it { is_expected.to be_an(Array) } + + it "returns matching ref object" do + expect(subject.length).to eq(1) + + ref = subject.first + + expect(ref).to be_a(Gitaly::ListRefsResponse::Reference) + expect(ref.name).to eq("refs/heads/master") + expect(ref.target).to be_a(String) + end + end + + context "when :ref_type is :tags" do + let(:params) do + { search: "v1.0.", ref_type: :tags } + end + + it { is_expected.to be_an(Array) } + + it "returns matching ref object" do + expect(subject.length).to eq(1) + + ref = subject.first + + expect(ref).to be_a(Gitaly::ListRefsResponse::Reference) + expect(ref.name).to eq("refs/tags/v1.0.0") + expect(ref.target).to be_a(String) + end + end + + context "when :ref_type is invalid" do + let(:params) do + { search: "master", ref_type: nil } + end + + it "raises an error" do + expect { subject }.to raise_error(described_class::UnknownRefTypeError) + end + end + end +end