diff --git a/lib/jenkins_api_client/job.rb b/lib/jenkins_api_client/job.rb index ef7cd751..3e336910 100644 --- a/lib/jenkins_api_client/job.rb +++ b/lib/jenkins_api_client/job.rb @@ -610,6 +610,16 @@ def list_all response_json.map { |job| job["name"] }.sort end + def multibranch_job_name_separator(job_name) + branch_regex = %r{/branch/} + if job_name =~ branch_regex + return job_name.split(branch_regex) + end + + nil + end + private :multibranch_job_name_separator + # Checks if the given job exists in Jenkins # # @param job_name [String] the name of the job to check @@ -617,7 +627,13 @@ def list_all # @return [Boolean] whether the job exists in jenkins or not # def exists?(job_name) - list(job_name).include?(job_name) + final_job_name = job_name + jobs = multibranch_job_name_separator(job_name) + if jobs + final_job_name = jobs.last + end + + list(job_name).include?(final_job_name) end # List all Jobs matching the given status @@ -653,13 +669,23 @@ def list_by_status(status, jobs = []) # def list(filter, ignorecase = true) @logger.info "Obtaining jobs matching filter '#{filter}'" - response_json = @client.api_get_request("") + + url_prefix = '' + final_filter = filter + + jobs = multibranch_job_name_separator(filter) + if jobs + url_prefix = "/job/#{path_encode jobs.first}" + final_filter = jobs.last + end + + response_json = @client.api_get_request(url_prefix) jobs = [] response_json["jobs"].each do |job| if ignorecase - jobs << job["name"] if job["name"] =~ /#{filter}/i + jobs << job["name"] if job["name"] =~ /#{final_filter}/i else - jobs << job["name"] if job["name"] =~ /#{filter}/ + jobs << job["name"] if job["name"] =~ /#{final_filter}/ end end jobs diff --git a/spec/unit_tests/job_spec.rb b/spec/unit_tests/job_spec.rb index acb96bf5..3e9e0b76 100644 --- a/spec/unit_tests/job_spec.rb +++ b/spec/unit_tests/job_spec.rb @@ -279,6 +279,17 @@ @sample_json_response) @job.exists?("test_job").should == true end + + it "accepts a multibranch job name and returns true if the job exists" do + msg = "/job/test_job" + mock_job_list_response = { + "jobs" => [ + {"name" => "alma"} + ] + } + @client.should_receive(:api_get_request).with(msg).and_return(mock_job_list_response) + @job.exists?("test_job/branch/alma").should == true + end end describe "#list_by_status" do @@ -300,6 +311,20 @@ "jobs" => ["test_job"]) @job.list("filter").class.should == Array end + + it "accepts a multibranch job name and returns jobs in the main job" do + mock_job_list_response = { + "jobs" => [ + {"name" => "alma"}, + {"name" => "almak"}, + {"name" => "almafa"}, + {"name" => "korte"} + ] + } + + @client.should_receive(:api_get_request).and_return(mock_job_list_response) + expect(@job.list("test_job/branch/alma")).to eq(['alma', 'almak', 'almafa']) + end end describe "#list_all_with_details" do