2018-07-05 06:18:17 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-09-21 10:15:12 -04:00
|
|
|
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)
|
|
|
|
|
2018-02-12 10:31:02 -05:00
|
|
|
branches = project.repository.merged_branch_names
|
|
|
|
# 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) }
|
2016-09-21 10:15:12 -04:00
|
|
|
|
2018-02-12 10:31:02 -05:00
|
|
|
branches.each do |branch|
|
|
|
|
DeleteBranchService.new(project, current_user).execute(branch)
|
2016-09-21 10:15:12 -04:00
|
|
|
end
|
|
|
|
end
|
2017-04-16 23:51:16 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-08-27 11:31:01 -04:00
|
|
|
# rubocop: disable CodeReuse/ActiveRecord
|
2017-04-16 23:51:16 -04:00
|
|
|
def merge_request_branch_names
|
|
|
|
# reorder(nil) is necessary for SELECT DISTINCT because default scope adds an ORDER BY
|
2018-10-26 12:19:28 -04:00
|
|
|
source_names = project.origin_merge_requests.opened.reorder(nil).distinct.pluck(:source_branch)
|
|
|
|
target_names = project.merge_requests.opened.reorder(nil).distinct.pluck(:target_branch)
|
2017-04-16 23:51:16 -04:00
|
|
|
(source_names + target_names).uniq
|
|
|
|
end
|
2018-08-27 11:31:01 -04:00
|
|
|
# rubocop: enable CodeReuse/ActiveRecord
|
2016-09-21 10:15:12 -04:00
|
|
|
end
|