BigW Consortium Gitlab

pivotaltracker_service.rb 1.66 KB
Newer Older
1 2 3
class PivotaltrackerService < Service
  include HTTParty

4 5 6
  API_ENDPOINT = 'https://www.pivotaltracker.com/services/v5/source_commits'

  prop_accessor :token, :restrict_to_branch
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  validates :token, presence: true, if: :activated?

  def title
    'PivotalTracker'
  end

  def description
    'Project Management Software (Source Commits Endpoint)'
  end

  def to_param
    'pivotaltracker'
  end

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

37 38 39 40
  def supported_events
    %w(push)
  end

41
  def execute(data)
42
    return unless supported_events.include?(data[:object_kind])
43
    return unless allowed_branch?(data[:ref])
44

45
    data[:commits].each do |commit|
Johannes Becker committed
46 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]
        }
      }
      PivotaltrackerService.post(
55
        API_ENDPOINT,
Johannes Becker committed
56 57 58 59 60 61
        body: message.to_json,
        headers: {
          'Content-Type' => 'application/json',
          'X-TrackerToken' => token
        }
      )
62 63
    end
  end
64 65 66 67 68 69 70 71 72 73 74

  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
75
end