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

    def execute
7 8
      @start_project = params[:start_project] || @project
      @start_branch = params[:start_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
    def commit_change(action)
      raise NotImplementedError unless repository.respond_to?(action)

29 30
      if @create_merge_request
        into = @commit.public_send("#{action}_branch_name")
31
        tree_branch = @start_branch
32 33 34 35 36 37
      else
        into = tree_branch = @target_branch
      end

      tree_id = repository.public_send(
        "check_#{action}_content", @commit, tree_branch)
38 39

      if tree_id
40
        validate_target_branch(into) if @create_merge_request
41

42 43 44 45 46 47
        repository.public_send(
          action,
          current_user,
          @commit,
          into,
          tree_id,
48 49
          start_project: @start_project,
          start_branch_name: @start_branch)
50

51 52
        success
      else
53
        error_msg = "Sorry, we cannot #{action.to_s.dasherize} this #{@commit.change_type_title(current_user)} automatically.
54
                     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."
55 56 57
        raise ChangeError, error_msg
      end
    end
P
P.S.V.R 已提交
58 59

    def check_push_permissions
60
      allowed = ::Gitlab::UserAccess.new(current_user, project: project).can_push_to_branch?(@target_branch)
P
P.S.V.R 已提交
61 62 63 64 65 66 67

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

      true
    end
68

69
    def validate_target_branch(new_branch)
P
P.S.V.R 已提交
70
      # Temporary branch exists and contains the change commit
71
      return if repository.find_branch(new_branch)
P
P.S.V.R 已提交
72

73 74
      result = ValidateNewBranchService.new(@project, current_user)
        .execute(new_branch)
P
P.S.V.R 已提交
75 76 77 78 79 80 81

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