change_service.rb 2.0 KB
Newer Older
P
P.S.V.R 已提交
1 2
module Commits
  class ChangeService < ::BaseService
3 4
    ValidationError = Class.new(StandardError)
    ChangeError = Class.new(StandardError)
P
P.S.V.R 已提交
5 6

    def execute
7 8
      @start_project = params[:start_project] || @project
      @start_branch = params[:start_branch]
P
P.S.V.R 已提交
9 10 11
      @target_branch = params[:target_branch]
      @commit = params[:commit]

12 13
      check_push_permissions

P
P.S.V.R 已提交
14 15 16 17 18 19
      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
      validate_target_branch if different_branch?
30

31 32 33 34 35 36 37
      repository.public_send(
        action,
        current_user,
        @commit,
        @target_branch,
        start_project: @start_project,
        start_branch_name: @start_branch)
38

39
      success
D
Douwe Maan 已提交
40
    rescue Repository::CreateTreeError
41
      error_msg = "Sorry, we cannot #{action.to_s.dasherize} this #{@commit.change_type_title(current_user)} automatically.
42
                     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."
43
      raise ChangeError, error_msg
44
    end
P
P.S.V.R 已提交
45 46

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

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

      true
    end
55

56
    def validate_target_branch
57 58
      result = ValidateNewBranchService.new(@project, current_user)
        .execute(@target_branch)
P
P.S.V.R 已提交
59 60 61 62 63

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

    def different_branch?
      @start_branch != @target_branch || @start_project != @project
    end
P
P.S.V.R 已提交
68 69
  end
end