debian-mirror-gitlab/app/services/commits/create_service.rb

87 lines
2.2 KiB
Ruby
Raw Normal View History

2018-11-18 11:00:15 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
module Commits
class CreateService < ::BaseService
ValidationError = Class.new(StandardError)
ChangeError = Class.new(StandardError)
def initialize(*args)
super
@start_project = params[:start_project] || @project
@start_branch = params[:start_branch]
@branch_name = params[:branch_name]
2019-05-18 00:54:41 +05:30
@force = params[:force] || false
2017-08-17 22:00:37 +05:30
end
def execute
validate!
new_commit = create_commit!
success(result: new_commit)
2018-12-13 13:39:08 +05:30
rescue ValidationError,
ChangeError,
Gitlab::Git::Index::IndexError,
Gitlab::Git::CommitError,
Gitlab::Git::PreReceiveError,
Gitlab::Git::CommandError => ex
2017-08-17 22:00:37 +05:30
error(ex.message)
end
private
def create_commit!
raise NotImplementedError
end
def raise_error(message)
raise ValidationError, message
end
def different_branch?
@start_branch != @branch_name || @start_project != @project
end
2019-05-18 00:54:41 +05:30
def force?
!!@force
end
2017-08-17 22:00:37 +05:30
def validate!
validate_permissions!
validate_on_branch!
2019-05-18 00:54:41 +05:30
validate_branch_existence!
2017-08-17 22:00:37 +05:30
validate_new_branch_name! if different_branch?
end
def validate_permissions!
allowed = ::Gitlab::UserAccess.new(current_user, project: project).can_push_to_branch?(@branch_name)
unless allowed
raise_error("You are not allowed to push into this branch")
end
end
def validate_on_branch!
if !@start_project.empty_repo? && !@start_project.repository.branch_exists?(@start_branch)
raise_error('You can only create or edit files when you are on a branch')
end
end
2019-05-18 00:54:41 +05:30
def validate_branch_existence!
if !project.empty_repo? && different_branch? && repository.branch_exists?(@branch_name) && !force?
2017-08-17 22:00:37 +05:30
raise_error("A branch called '#{@branch_name}' already exists. Switch to that branch in order to make changes")
end
end
def validate_new_branch_name!
2019-05-18 00:54:41 +05:30
result = ValidateNewBranchService.new(project, current_user).execute(@branch_name, force: force?)
2017-08-17 22:00:37 +05:30
if result[:status] == :error
raise_error("Something went wrong when we tried to create '#{@branch_name}' for you: #{result[:message]}")
end
end
end
end