gitlab-org--gitlab-foss/app/services/delete_merged_branches_service.rb
Toon Claes ca3c868567 When deleting merged branches, ignore protected tags
In gitlab-org/gitlab-ce!13251 wildcard Protected Branches were handled
properly when deleting all merged branches. But this fix wasn't that
good. It also checked branch names against Protected Tags. That's not
correct.

This change will **only** check if there is a Protected Branch
matching the merged branch, and ignores Protected Tags.

Closes gitlab-org/gitlab-ce#39732.
2017-11-07 16:58:36 +01:00

32 lines
1.2 KiB
Ruby

class DeleteMergedBranchesService < BaseService
def async_execute
DeleteMergedBranchesWorker.perform_async(project.id, current_user.id)
end
def execute
raise Gitlab::Access::AccessDeniedError unless can?(current_user, :push_code, project)
# n+1: https://gitlab.com/gitlab-org/gitlab-ce/issues/37438
Gitlab::GitalyClient.allow_n_plus_1_calls do
branches = project.repository.branch_names
branches = branches.select { |branch| project.repository.merged_to_root_ref?(branch) }
# Prevent deletion of branches relevant to open merge requests
branches -= merge_request_branch_names
# Prevent deletion of protected branches
branches = branches.reject { |branch| ProtectedBranch.protected?(project, branch) }
branches.each do |branch|
DeleteBranchService.new(project, current_user).execute(branch)
end
end
end
private
def merge_request_branch_names
# reorder(nil) is necessary for SELECT DISTINCT because default scope adds an ORDER BY
source_names = project.origin_merge_requests.opened.reorder(nil).uniq.pluck(:source_branch)
target_names = project.merge_requests.opened.reorder(nil).uniq.pluck(:target_branch)
(source_names + target_names).uniq
end
end