summaryrefslogtreecommitdiff
path: root/app/services/merge_requests/merge_service.rb
blob: 2107529a21a1a00beb86818399fd62f11d1056c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module MergeRequests
  # MergeService class
  #
  # 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

    def execute(merge_request, commit_message)
      @commit_message = commit_message
      @merge_request = merge_request

      unless @merge_request.mergeable?
        return error('Merge request is not mergeable')
      end

      merge_request.in_locked_state do
        if merge_changes
          after_merge
          success
        else
          error('Can not merge changes')
        end
      end
    end

    private

    def merge_changes
      if sha = commit
        after_commit(sha, merge_request.target_branch)
      end
    end

    def commit
      committer = repository.user_to_comitter(current_user)

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

      repository.merge(merge_request.source_sha, merge_request.target_branch, options)
    end

    def after_commit(sha, branch)
      PostCommitService.new(project, current_user).execute(sha, branch)
    end

    def after_merge
      MergeRequests::PostMergeService.new(project, current_user).execute(merge_request)
    end
  end
end