Skip to content

Instantly share code, notes, and snippets.

@alexblackie
Created November 3, 2015 20:46
Show Gist options
  • Save alexblackie/7f55ccf7f49056c0d5b4 to your computer and use it in GitHub Desktop.
Save alexblackie/7f55ccf7f49056c0d5b4 to your computer and use it in GitHub Desktop.
Meant to be run in a Jenkins job; marks stories in Pivotal as "Delivered" if their IDs are mentioned in a commit that's part of the current Jenkins build changeset.
require "net/http"
require "json"
require "pry"
# Wrapper around the Jenkins JSON API
class Jenkins
# @param [string] jenkins_user - a Jenkins user with at least read access
# @param [string] token - Jenkins API token for the user
# @param [string] job - Jenkins job name
def initialize(jenkins_user, token, job)
@token = token
@jenkins_user = jenkins_user
@job = job
end
# Hits the Jenkins API and returns the list of changes for a build. Uses the
# Jenkins-provided `BUILD_NUMBER` environment variable to determine which
# build's changes to fetch.
#
# @return [array] list of hashes of commits and their metadata
def changeset_commits
uri = URI("https://#{ENV["JENKINS_URL"]}/job/#{@job}/#{ENV["BUILD_NUMBER"]}/api/json")
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
req = Net::HTTP::Get.new(uri)
req.basic_auth @jenkins_user, @token
JSON.parse(http.request(req).body)
end
response["changeSet"]["items"]
end
end
# Wrapper around the PivotalTracker HTTP API.
class Tracker
# @param [string] token - the Pivotal Tracker API token
# @param [to_s] project - the Pivotal Tracker project ID
def initialize(token, project)
@token = token
@project = project
end
# Mark the given story as being in the 'Delivered' state
#
# @param [to_s] story_id - the ID of the story to be delivered
def deliver(story_id)
uri = URI("https://www.pivotaltracker.com/services/v5/projects/#{@project}/stories/#{story_id}")
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
req = Net::HTTP::Put.new(uri)
req["X-TrackerToken"] = @token
req["Content-Type"] = "application/json"
body = JSON.generate({current_state: "delivered"})
http.request(req, body)
end
end
end
# Main entrypoint
class PivotalDeliverance
def initialize
@jenkins = Jenkins.new(ENV["PD_JENKINS_USER"], ENV["PD_JENKINS_API_KEY"], ENV["PD_JENKINS_JOB_NAME"])
@tracker = Tracker.new(ENV["PD_TRACKER_API_KEY"], ENV["PD_TRACKER_PROJECT_ID"])
end
def deliver_stories_from_changelog
@jenkins.changeset_commits.each do |c|
# skip if commit doesn't reference a ticket
next unless c["comment"].match /Finishes #\d+/
story_id = c["comment"].match(/\[Finishes #(\d+)\]/).captures.first
@tracker.deliver(story_id)
end
end
end
# ------------------------------------------------------------------------------
PivotalDeliverance.new.deliver_stories_from_changelog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment