Read about our upcoming Code of Conduct on this issue

pivotaltracker_service.rb 1.78 KB
Newer Older
1
2
# frozen_string_literal: true

3
class PivotaltrackerService < Service
Douwe Maan's avatar
Douwe Maan committed
4
  API_ENDPOINT = 'https://www.pivotaltracker.com/services/v5/source_commits'.freeze
5
6

  prop_accessor :token, :restrict_to_branch
7
8
9
10
11
12
13
  validates :token, presence: true, if: :activated?

  def title
    'PivotalTracker'
  end

  def description
14
    s_('PivotalTrackerService|Project Management Software (Source Commits Endpoint)')
15
16
  end

17
  def self.to_param
18
19
20
21
22
    'pivotaltracker'
  end

  def fields
    [
23
24
25
      {
        type: 'text',
        name: 'token',
26
        placeholder: s_('PivotalTrackerService|Pivotal Tracker API token.'),
27
        required: true
28
29
30
31
      },
      {
        type: 'text',
        name: 'restrict_to_branch',
32
33
        placeholder: s_('PivotalTrackerService|Comma-separated list of branches which will be ' \
          'automatically inspected. Leave blank to include all branches.')
34
      }
35
36
37
    ]
  end

38
  def self.supported_events
39
40
41
    %w(push)
  end

Douwe Maan's avatar
Douwe Maan committed
42
  def execute(data)
43
    return unless supported_events.include?(data[:object_kind])
44
    return unless allowed_branch?(data[:ref])
45

Douwe Maan's avatar
Douwe Maan committed
46
    data[:commits].each do |commit|
Johannes Becker's avatar
Johannes Becker committed
47
48
49
50
51
52
53
54
      message = {
        'source_commit' => {
          'commit_id' => commit[:id],
          'author' => commit[:author][:name],
          'url' => commit[:url],
          'message' => commit[:message]
        }
      }
55
      Gitlab::HTTP.post(
56
        API_ENDPOINT,
Johannes Becker's avatar
Johannes Becker committed
57
58
59
60
61
62
        body: message.to_json,
        headers: {
          'Content-Type' => 'application/json',
          'X-TrackerToken' => token
        }
      )
63
64
    end
  end
65
66
67
68
69
70
71
72
73
74
75

  private

  def allowed_branch?(ref)
    return true unless ref.present? && restrict_to_branch.present?

    branch = Gitlab::Git.ref_name(ref)
    allowed_branches = restrict_to_branch.split(',').map(&:strip)

    branch.present? && allowed_branches.include?(branch)
  end
76
end