2018-07-17 12:50:37 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-07-28 00:04:57 -04:00
|
|
|
module MergeRequests
|
|
|
|
class GetUrlsService < BaseService
|
|
|
|
attr_reader :project
|
|
|
|
|
|
|
|
def initialize(project)
|
|
|
|
@project = project
|
|
|
|
end
|
|
|
|
|
|
|
|
def execute(changes)
|
2017-03-17 08:35:39 -04:00
|
|
|
return [] unless project.printing_merge_request_link_enabled
|
|
|
|
|
2016-07-28 00:04:57 -04:00
|
|
|
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)
|
2017-03-16 11:22:09 -04:00
|
|
|
merge_requests.index_by(&:source_branch)
|
2016-07-28 00:04:57 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def get_branches(changes)
|
2016-08-11 20:39:18 -04:00
|
|
|
return [] if project.empty_repo?
|
2016-08-01 18:31:21 -04:00
|
|
|
return [] unless project.merge_requests_enabled?
|
2016-08-11 20:39:18 -04:00
|
|
|
|
2016-07-28 00:04:57 -04:00
|
|
|
changes_list = Gitlab::ChangesList.new(changes)
|
|
|
|
changes_list.map do |change|
|
|
|
|
next unless Gitlab::Git.branch_ref?(change[:ref])
|
2016-08-11 20:39:18 -04:00
|
|
|
|
|
|
|
# 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
|
2016-07-28 00:04:57 -04:00
|
|
|
end.compact
|
|
|
|
end
|
|
|
|
|
|
|
|
def url_for_new_merge_request(branch_name)
|
2018-11-07 08:32:20 -05:00
|
|
|
merge_request_params = { source_branch: branch_name }
|
|
|
|
url = Gitlab::Routing.url_helpers.project_new_merge_request_url(project, merge_request: merge_request_params)
|
2016-07-28 00:04:57 -04:00
|
|
|
{ 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
|
2017-06-29 13:06:35 -04:00
|
|
|
url = Gitlab::Routing.url_helpers.project_merge_request_url(target_project, merge_request)
|
2016-07-28 00:04:57 -04:00
|
|
|
{ branch_name: merge_request.source_branch, url: url, new_merge_request: false }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|