Read about our upcoming Code of Conduct on this issue

get_urls_service.rb 2.02 KB
Newer Older
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
module MergeRequests
  class GetUrlsService < BaseService
    attr_reader :project

    def initialize(project)
      @project = project
    end

    def execute(changes)
      branches = get_branches(changes)
      merge_requests_map = opened_merge_requests_from_source_branches(branches)
      branches.map do |branch|
        existing_merge_request = merge_requests_map[branch]
        if existing_merge_request
          url_for_existing_merge_request(existing_merge_request)
        else
          url_for_new_merge_request(branch)
        end
      end
    end

    private

    def opened_merge_requests_from_source_branches(branches)
      merge_requests = MergeRequest.from_project(project).opened.from_source_branches(branches)
      merge_requests.inject({}) do |hash, mr|
        hash[mr.source_branch] = mr
        hash
      end
    end

    def get_branches(changes)
33
      return [] if project.empty_repo?
Felipe Artur's avatar
Felipe Artur committed
34
      return [] unless project.merge_requests_enabled?
35

36
37
38
      changes_list = Gitlab::ChangesList.new(changes)
      changes_list.map do |change|
        next unless Gitlab::Git.branch_ref?(change[:ref])
39
40
41
42
43
44
45
46
47

        # Deleted branch
        next if Gitlab::Git.blank_ref?(change[:newrev])

        # Default branch
        branch_name = Gitlab::Git.branch_name(change[:ref])
        next if branch_name == project.default_branch

        branch_name
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
      end.compact
    end

    def url_for_new_merge_request(branch_name)
      merge_request_params = { source_branch: branch_name }
      url = Gitlab::Routing.url_helpers.new_namespace_project_merge_request_url(project.namespace, project, merge_request: merge_request_params)
      { branch_name: branch_name, url: url, new_merge_request: true }
    end

    def url_for_existing_merge_request(merge_request)
      target_project = merge_request.target_project
      url = Gitlab::Routing.url_helpers.namespace_project_merge_request_url(target_project.namespace, target_project, merge_request)
      { branch_name: merge_request.source_branch, url: url, new_merge_request: false }
    end
  end
end