Skip to content

Instantly share code, notes, and snippets.

@syncrou
Last active July 13, 2016 19:31
Show Gist options
  • Save syncrou/848bae9d83c75fa4525310e7071df853 to your computer and use it in GitHub Desktop.
Save syncrou/848bae9d83c75fa4525310e7071df853 to your computer and use it in GitHub Desktop.
Pivotal Tracker Hook
#! /usr/bin/env ruby
require 'rubygems'
require 'net/https'
class PivotalHook
PT_API_KEY = raise "Please add PT API KEY"
def self.post
commit_log = `git log -1`
parts = commit_log.split("\n")
id = parts[0]
author = parts[1]
date = parts[2]
log = parts[4..-1].join("\n")
current_remote_path = `git config --get remote.origin.url`.chomp.split(":")[1].gsub(".git","")
commit_id = id.gsub("commit ",'')
message = {
'id' => commit_id,
'author' => author.gsub("Author: ",'').gsub(/\s\<.+/,''),
'date' => date,
'url' => "http://github.com/#{current_remote_path}/commit/#{commit_id}",
'log' => log
}
task_id_regex = /www\.pivotaltracker\.com\/story\/show\/(\d*)/i
if task_id_regex =~ message['log']
api_key = PT_API_KEY
story_id = $1
post_to_pivotal_tracker(api_key, story_id, message)
else
puts "Didn't find a message to post to Pivotal"
end
end
private
# Postback to PivotalTracker, through HTTP connection
def self.post_to_pivotal_tracker(api_key, story_id, commit)
http = Net::HTTP.new 'www.pivotaltracker.com', 80
http.use_ssl = false
headers = {'X-TrackerToken' => api_key, 'Content-type' => 'application/xml'}
path = "http://www.pivotaltracker.com/services/v3/source_commits"
data = pivotal_comment_message_from(commit, story_id)
#puts "Pushing commit message (#{data}) over API (api_key: #{api_key}) to path: #{path}"
begin
http.post path, data, headers
puts ".. sent."
rescue => e
puts "Problem sending to Pivotal: #{e.inspect}"
end
end
# Creates XML message for PivotalTracker
def self.pivotal_comment_message_from(commit, story_id)
commit_message = commit['log'].slice(0,commit['log'].index("\n") || 500 )
"<source_commit><message>[\##{story_id}] #{commit_message}</message><author>#{commit['author']}</author><commit_id>#{commit['id'].slice(0,7)}</commit_id><url>#{commit['url']}</url></source_commit>"
end
end
PivotalHook.post
@syncrou
Copy link
Author

syncrou commented Jul 13, 2016

Install this file into .git/hooks/post-commit and chmod 755 .git/hooks/post-commit

You may need to modify how the remote-url is getting generated - mine is set up as origin (see line 16)

Don't forget to add your PT_API_KEY (line 7)

Sample output once a comment is posted:
postcommithookpt

@chrisarcand
Copy link

Awesome!

@chrisarcand
Copy link

It looks like PIVOTAL_TRACKER on Line 7 isn't used... @syncrou?

@syncrou
Copy link
Author

syncrou commented Jul 13, 2016

@chrisarcand - Just realized that myself -Thanks! - Pulled it out and updated the comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment