push_data_builder.rb 2.56 KB
Newer Older
1 2
module Gitlab
  class PushDataBuilder
3 4 5 6 7 8 9 10 11
    class << self
      # Produce a hash of post-receive data
      #
      # data = {
      #   before: String,
      #   after: String,
      #   ref: String,
      #   user_id: String,
      #   user_name: String,
12
      #   user_email: String
13 14 15 16 17 18 19 20 21 22 23 24 25 26
      #   project_id: String,
      #   repository: {
      #     name: String,
      #     url: String,
      #     description: String,
      #     homepage: String,
      #   },
      #   commits: Array,
      #   total_commits_count: Fixnum
      # }
      #
      def build(project, user, oldrev, newrev, ref, commits = [])
        # Total commits count
        commits_count = commits.size
27

28 29
        # Get latest 20 commits ASC
        commits_limited = commits.last(20)
30

31 32
        # Hash to be passed as post_receive_data
        data = {
33
          object_kind: "push",
34 35 36 37 38 39
          before: oldrev,
          after: newrev,
          ref: ref,
          checkout_sha: checkout_sha(project.repository, newrev, ref),
          user_id: user.id,
          user_name: user.name,
40
          user_email: user.email,
41 42 43 44 45 46
          project_id: project.id,
          repository: {
            name: project.name,
            url: project.url_to_repo,
            description: project.description,
            homepage: project.web_url,
47 48 49
            git_http_url: project.http_url_to_repo,
            git_ssh_url: project.ssh_url_to_repo,
            visibility_level: project.visibility_level
50 51 52 53
          },
          commits: [],
          total_commits_count: commits_count
        }
54

55 56 57 58 59 60
        # For performance purposes maximum 20 latest commits
        # will be passed as post receive hook data.
        commits_limited.each do |commit|
          data[:commits] << commit.hook_attrs(project)
        end

61
        data[:commits] = "" if data[:commits].count == 0
62
        data
63 64
      end

65 66 67 68 69 70
      # This method provide a sample data generated with
      # existing project and commits to test web hooks
      def build_sample(project, user)
        commits = project.repository.commits(project.default_branch, nil, 3)
        build(project, user, commits.last.id, commits.first.id, "refs/heads/#{project.default_branch}", commits)
      end
71

72 73 74 75
      def checkout_sha(repository, newrev, ref)
        if newrev != Gitlab::Git::BLANK_SHA && ref.start_with?('refs/tags/')
          tag_name = Gitlab::Git.extract_ref_name(ref)
          tag = repository.find_tag(tag_name)
76 77 78 79 80

          if tag
            commit = repository.commit(tag.target)
            commit.try(:sha)
          end
81 82 83 84
        else
          newrev
        end
      end
85 86 87
    end
  end
end