change_service.rb 2.4 KB
Newer Older
P
P.S.V.R 已提交
1 2 3 4 5 6 7
module Commits
  class ChangeService < ::BaseService
    class ValidationError < StandardError; end
    class ChangeError < StandardError; end

    def execute
      @source_project = params[:source_project] || @project
8
      @source_branch = params[:source_branch]
P
P.S.V.R 已提交
9 10 11 12 13 14 15 16 17 18 19
      @target_branch = params[:target_branch]
      @commit = params[:commit]
      @create_merge_request = params[:create_merge_request].present?

      check_push_permissions unless @create_merge_request
      commit
    rescue Repository::CommitError, Gitlab::Git::Repository::InvalidBlobName, GitHooksService::PreReceiveError,
           ValidationError, ChangeError => ex
      error(ex.message)
    end

20 21
    private

P
P.S.V.R 已提交
22 23 24 25
    def commit
      raise NotImplementedError
    end

26 27 28 29 30 31 32
    def commit_change(action)
      raise NotImplementedError unless repository.respond_to?(action)

      into = @create_merge_request ? @commit.public_send("#{action}_branch_name") : @target_branch
      tree_id = repository.public_send("check_#{action}_content", @commit, @target_branch)

      if tree_id
33
        validate_target_branch(into) if @create_merge_request
34

35 36 37 38 39 40
        repository.public_send(
          action,
          current_user,
          @commit,
          into,
          tree_id,
41
          source_project: @source_project,
42
          source_branch_name: @source_branch)
43

44 45
        success
      else
46
        error_msg = "Sorry, we cannot #{action.to_s.dasherize} this #{@commit.change_type_title(current_user)} automatically.
47
                     A #{action.to_s.dasherize} may have already been performed with this #{@commit.change_type_title(current_user)}, or a more recent commit may have updated some of its content."
48 49 50
        raise ChangeError, error_msg
      end
    end
P
P.S.V.R 已提交
51 52

    def check_push_permissions
53
      allowed = ::Gitlab::UserAccess.new(current_user, project: project).can_push_to_branch?(@target_branch)
P
P.S.V.R 已提交
54 55 56 57 58 59 60

      unless allowed
        raise ValidationError.new('You are not allowed to push into this branch')
      end

      true
    end
61

62
    def validate_target_branch(new_branch)
P
P.S.V.R 已提交
63
      # Temporary branch exists and contains the change commit
64
      return if repository.find_branch(new_branch)
P
P.S.V.R 已提交
65

66 67
      result = ValidateNewBranchService.new(@project, current_user).
        execute(new_branch)
P
P.S.V.R 已提交
68 69 70 71 72 73 74

      if result[:status] == :error
        raise ChangeError, "There was an error creating the source branch: #{result[:message]}"
      end
    end
  end
end