2019-12-03 13:06:49 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Branches
|
|
|
|
class CreateService < BaseService
|
2021-05-25 14:10:42 -04:00
|
|
|
def execute(branch_name, ref, create_default_branch_if_empty: true)
|
|
|
|
create_default_branch if create_default_branch_if_empty && project.empty_repo?
|
2019-12-03 13:06:49 -05:00
|
|
|
|
|
|
|
result = ::Branches::ValidateNewService.new(project).execute(branch_name)
|
|
|
|
|
|
|
|
return result if result[:status] == :error
|
|
|
|
|
2021-07-07 11:07:24 -04:00
|
|
|
begin
|
|
|
|
new_branch = repository.add_branch(current_user, branch_name, ref)
|
|
|
|
rescue Gitlab::Git::CommandError => e
|
|
|
|
return error("Failed to create branch '#{branch_name}': #{e}")
|
|
|
|
end
|
2019-12-03 13:06:49 -05:00
|
|
|
|
|
|
|
if new_branch
|
|
|
|
success(new_branch)
|
|
|
|
else
|
2021-07-07 11:07:24 -04:00
|
|
|
error("Failed to create branch '#{branch_name}': invalid reference name '#{ref}'")
|
2019-12-03 13:06:49 -05:00
|
|
|
end
|
2020-08-05 23:10:05 -04:00
|
|
|
rescue Gitlab::Git::PreReceiveError => e
|
2022-02-01 10:18:50 -05:00
|
|
|
Gitlab::ErrorTracking.log_exception(e, pre_receive_message: e.raw_message, branch_name: branch_name, ref: ref)
|
2020-08-05 23:10:05 -04:00
|
|
|
error(e.message)
|
2019-12-03 13:06:49 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def success(branch)
|
|
|
|
super().merge(branch: branch)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2021-05-25 14:10:42 -04:00
|
|
|
def create_default_branch
|
2019-12-03 13:06:49 -05:00
|
|
|
project.repository.create_file(
|
|
|
|
current_user,
|
|
|
|
'/README.md',
|
|
|
|
'',
|
|
|
|
message: 'Add README.md',
|
2021-05-25 14:10:42 -04:00
|
|
|
branch_name: project.default_branch_or_main
|
2019-12-03 13:06:49 -05:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|