merge_service.rb 1.29 KB
Newer Older
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
1 2 3
module MergeRequests
  # MergeService class
  #
4 5 6 7 8 9 10
  # Do git merge and in case of success
  # mark merge request as merged and execute all hooks and notifications
  # Executed when you do merge via GitLab UI
  #
  class MergeService < MergeRequests::BaseService
    attr_reader :merge_request, :commit_message

11
    def execute(merge_request, commit_message)
12 13
      @commit_message = commit_message
      @merge_request = merge_request
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
14

15 16 17 18 19
      unless @merge_request.mergeable?
        return error('Merge request is not mergeable')
      end

      merge_request.in_locked_state do
20
        if commit
21 22 23 24 25 26 27 28 29 30 31
          after_merge
          success
        else
          error('Can not merge changes')
        end
      end
    end

    private

    def commit
Stan Hu's avatar
Stan Hu committed
32
      committer = repository.user_to_committer(current_user)
33 34 35 36 37 38 39

      options = {
        message: commit_message,
        author: committer,
        committer: committer
      }

40
      repository.merge(current_user, merge_request.source_sha, merge_request.target_branch, options)
41
    rescue StandardError => e
42 43 44
      merge_request.update(merge_error: "Something went wrong during merge")
      Rails.logger.error(e.message)
      return false
45
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
46

47 48
    def after_merge
      MergeRequests::PostMergeService.new(project, current_user).execute(merge_request)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
49 50 51
    end
  end
end