Skip to content

Instantly share code, notes, and snippets.

@pewniak747
Created April 10, 2012 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pewniak747/2352380 to your computer and use it in GitHub Desktop.
Save pewniak747/2352380 to your computer and use it in GitHub Desktop.
git post-receive pivotal hook
#!/usr/bin/env ruby
# encoding: UTF-8
require 'net/http'
require 'nokogiri'
class GitLogs
attr_accessor :raw_log, :logs
def initialize old_ref, new_ref
self.raw_log = `git log --no-color --format=short #{old_ref}..#{new_ref}`.force_encoding('utf-8')
self.logs = []
parse!
self
end
def parse!
regexp = /commit\ (.*)\nAuthor:\ (.*)\n\n\s*(.*)/i
raw_log.scan(regexp).to_a.each do |match|
self.logs << GitLog.new(match[0], match[1], match[2])
end
end
def pivotal_sync!
Pivotal.new(logs.reverse).send!
end
end
class GitLog
attr_accessor :raw_log, :hash, :author, :message
def initialize hash, author, message
self.hash = hash
self.author = author
self.message = message
end
def to_xml
Nokogiri::XML::Builder.new do |xml|
xml.source_commit {
xml.commit_id self.hash
xml.author self.author
xml.message self.message
}
end.to_xml
end
end
class Pivotal
attr_accessor :git_logs, :tracker_token
BASE_URI = URI('http://www.pivotaltracker.com/')
def initialize git_logs
self.git_logs = git_logs
self.tracker_token = get_token
end
def get_token
`git config --get pivotal.token`.strip
end
def send!
Net::HTTP.start(BASE_URI.host) do |http|
git_logs.each do |git_log|
request = Net::HTTP::Post.new('/services/v3/source_commits')
request['X-TrackerToken'] = tracker_token
request['Content-type'] = 'application/xml'
request.body = git_log.to_xml
response = http.request(request)
end
end
end
end
out = STDIN.read
old_ref, new_ref, ref_name = out.split
GitLogs.new(old_ref, new_ref).pivotal_sync!
@leek
Copy link

leek commented May 4, 2012

For installation of nokogiri (a dependency) on Ubuntu:

sudo apt-get install libxslt-dev libxml2-dev
sudo gem install nokogiri

I wanted this to work for only a specific branch, so here is my post-receive file:

#!/bin/bash

while read oldrev newrev ref
do
  branch=`echo $ref | cut -d/ -f3`
  echo "Detected branch: $branch"

  #
  # Update Pivotal Tracker
  if [ "develop" == "$branch" ]; then
    echo "Updating Pivotal Tracker..."
    echo "$oldrev $newrev $ref" | ./post-receive-pivotal
  fi
done

Also - for this to work with Ruby 1.8.7, add the following to the top of post-receive-pivotal:

#!/usr/bin/env ruby
# encoding: UTF-8

require 'net/http'
require 'nokogiri'

class String
  def force_encoding(enc)
    self
  end
end

# ... snip ...

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