change_service.rb 2.1 KB
Newer Older
P
P.S.V.R 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
module Commits
  class ChangeService < ::BaseService
    class ValidationError < StandardError; end
    class ChangeError < StandardError; end

    def execute
      @source_project = params[:source_project] || @project
      @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

19 20
    private

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

25 26 27 28 29 30 31
    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
32
        validate_target_branch(into) if @create_merge_request
33 34 35 36 37 38 39 40 41

        repository.public_send(action, current_user, @commit, into, tree_id)
        success
      else
        error_msg = "Sorry, we cannot #{action.to_s.dasherize} this #{@commit.change_type_title} automatically.
                     It may have already been #{action.to_s.dasherize}, or a more recent commit may have updated some of its content."
        raise ChangeError, error_msg
      end
    end
P
P.S.V.R 已提交
42 43

    def check_push_permissions
44
      allowed = ::Gitlab::UserAccess.new(current_user, project: project).can_push_to_branch?(@target_branch)
P
P.S.V.R 已提交
45 46 47 48 49 50 51

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

      true
    end
52

53
    def validate_target_branch(new_branch)
P
P.S.V.R 已提交
54
      # Temporary branch exists and contains the change commit
55
      return if repository.find_branch(new_branch)
P
P.S.V.R 已提交
56

57 58
      result = ValidateNewBranchService.new(@project, current_user).
        execute(new_branch)
P
P.S.V.R 已提交
59 60 61 62 63 64 65

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