summaryrefslogtreecommitdiff
path: root/app/services/issues/related_branches_service.rb
blob: 46076218857861269e4a5a29de0022778081810a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true

# This service fetches all branches containing the current issue's ID, except for
# those with a merge request open referencing the current issue.
module Issues
  class RelatedBranchesService < Issues::BaseService
    def execute(issue)
      branch_names = branches_with_iid_of(issue) - branches_with_merge_request_for(issue)
      branch_names.map { |branch_name| branch_data(branch_name) }
    end

    private

    def branch_data(branch_name)
      {
        name: branch_name,
        pipeline_status: pipeline_status(branch_name)
      }
    end

    def pipeline_status(branch_name)
      branch = project.repository.find_branch(branch_name)
      target = branch&.dereferenced_target

      return unless target

      pipeline = project.pipeline_for(branch_name, target.sha)
      pipeline.detailed_status(current_user) if can?(current_user, :read_pipeline, pipeline)
    end

    def branches_with_merge_request_for(issue)
      Issues::ReferencedMergeRequestsService
        .new(project, current_user)
        .referenced_merge_requests(issue)
        .map(&:source_branch)
    end

    def branches_with_iid_of(issue)
      project.repository.branch_names.select do |branch|
        branch =~ /\A#{issue.iid}-(?!\d+-stable)/i
      end
    end
  end
end