summaryrefslogtreecommitdiff
path: root/app/services/commit_service.rb
blob: 92d1585840b3c9c462fcc0e9e174711508820095 (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
require 'securerandom'

class CommitService
  class PreReceiveError < StandardError; end
  class CommitError < StandardError; end

  def self.transaction(project, current_user, ref)
    repository = project.repository
    path_to_repo = repository.path_to_repo
    empty_repo = repository.empty?

    # Create temporary ref
    random_string = SecureRandom.hex
    tmp_ref = "refs/tmp/#{random_string}/head"

    unless empty_repo
      target = repository.find_branch(ref).target
      repository.rugged.references.create(tmp_ref, target)
    end

    # Make commit in tmp ref
    sha = yield(tmp_ref)

    unless sha
      raise CommitError.new('Failed to create commit')
    end

    # Run GitLab pre-receive hook
    status = PreCommitService.new(project, current_user).execute(sha, ref)

    if status
      if empty_repo
        # Create branch
        repository.rugged.references.create(Gitlab::Git::BRANCH_REF_PREFIX + ref, sha)
      else
        # Update head
        repository.rugged.references.update(Gitlab::Git::BRANCH_REF_PREFIX + ref, sha)
      end

      # Run GitLab post receive hook
      PostCommitService.new(project, current_user).execute(sha, ref)
    else
      # Remove tmp ref and return error to user
      repository.rugged.references.delete(tmp_ref)

      raise PreReceiveError.new('Commit was rejected by pre-reveive hook')
    end
  end
end