We switched to Git this year, and we now use Git almost exclusively at Art of Mission. We’ve even moved over most of our old svn repositories.

One thing we wanted to do recently was to post commit messages into our Backpack journal. Turns out it is very easy with Git and a little bit of Ruby code.

This would go in .git/hooks/post-commit (make sure to make the that file executable):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env ruby
require 'rexml/document'
require 'net/http'

# Customize these values: 
  # Your backpack account:
ACCOUNT = "yourbackpacksubdomain"
  # Your backpack user id:
USER_ID = 123456
  # Your token (you might want to put this in a shell variable):
TOKEN   = '1234567890987654321234567890987654321'
PROJECT = "my-project"

GIT     = `which git`.strip

def build_commit_message
  text = `#{GIT} log --all -n 1`
  lines = text.split("\n\ncommit ")

  revision = text[/([a-f0-9]{32})/]
  commit_author  = `#{GIT} show --pretty=format:"%an" #{revision} | sed q`.chomp
  commit_log     = `#{GIT} show --pretty=format:"%s" #{revision}  | sed q`.chomp
  # Additional useful data...
  # commit_date    = `#{GIT} show --pretty=format:"%aD" #{revision} | sed q`.chomp
  # commit_changed = `#{GIT}-diff-tree --name-status #{revision}    | sed -n '$p'`
  
  "[#{PROJECT}] #{commit_log}"
end

# Build the Backpack xml snippet:
def build_request(message)
  doc = REXML::Document.new
  request = doc.add_element 'request'
  request.add_element('token').add_text TOKEN
  journal_entry = request.add_element('journal-entry')
  journal_entry.add_element('body').add_text(message)
  return doc
end

# Post the request to Backpack:
def send_to_journal(message)
  doc = build_request(message)
  http = Net::HTTP.new("#{ACCOUNT}.backpackit.com")
  response = http.post("/users/#{USER_ID}/journal_entries.xml", doc.to_s, {'Content-Type' => 'application/xml'})
end

# Do it:
send_to_journal(build_commit_message)

2 Responses to “Post Git Commit Messages to Backpack Journal”

  1. Jeff Berg Says:

    One thing I found is that you need to define the PROJECT variable or it will error out. ;-)

  2. Ryan Says:

    Good catch Jeff – I updated the example.

Sorry, comments are closed for this article.