Git integration with Hudson and Trac.

As I mentioned in my previous post about Git at Slide, I wanted to answer some questions that we had to answer to migrate to Git for our development workflow. One of the major questions that had to be answered, especially for our QA department to sign off on the idea was:

How will Git integrate with Hudson, Trac and our other pieces of development infrastructure?

For us to use any version control system, centralized or decentralized, there had to be a "central" point for changes to integrate into in order for us to properly test releases and then ship them to the live site. With this requirement, we oriented our use of Git around a centralized repository which developers pull from, and push to on a regular basis.

In order for Git to integrate into Trac and Hudson, we opted for baking the functionality we needed into the post-receive hook on the centralized repository instead of relying on GitTrac, or the Hudson Git plugin to do what we needed it do to.

You can find the script below, or in this GitHub repository. The script requires the Trac XML-RPC plugin to be installed in order to properly annotate tickets when changes are pushed into the central repository. The notation syntaxes that the post-receive.py script supports in commit messages are:

re #12345
qa #12345
attn bbum,fspeirs

As one might expect, the first notation: "re #12345" will simply annotate a ticket with the commit message and the branch in which the commit was pushed into. The "qa #12345" notation part of an internal notation of marking tickets in Trac as "Ready for QA", which let's our QA engineers know when tickets are ready to be verified; a "qa" note in a commit message will reference the commit and change the status of the ticket in question. The final notation that the script supports: "attn bbum,fspeirs" is purely for calling attention to a code change, or to ask for a code review. When a commit is pushed to the central repository with "attn" in the commit message, an email with the commit message and diff will be emailed to the specified recipients.

In addition to updating Trac tickets, pushes into any branch that have a Hudson job affiliated will use the Hudson External API to queue a build for that branch. In effect, it you "git push origin master", the post-receive.py script will ping Hudson and ask it to queue a build of the "master" job.

I have included the script inline below for those weary of clicking links like this one to the GitHub repository containing the script. Enjoy :)

  1. '''
  2. Copyright (c) 2008 Slide, Inc
  3.  
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10.  
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13.  
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. '''
  22.  
  23. '''
  24. For questions, patches, etc contact R. Tyler Ballance <[email protected]>
  25. '''
  26. import getpass
  27. import os
  28. import re
  29. import socket
  30. import smtplib
  31. import sys
  32. import time
  33. import xmlrpclib
  34.  
  35. from optparse import OptionParser
  36.  
  37. MAIL_SERVER = 'your_mail_server.com'
  38. MAIL_SUFFIX = '@mycompany.com'
  39. BUILD_HUDSON = True
  40. HUDSON_URL = 'http://hudson'
  41. TRAC_XMLRPC_URL = 'URL_TO_TRAC/projects/MYPROJECT/login/xmlrpc'
  42.  
  43. def rpcProxy(user='qatracbot', password=None):
  44. password = password or os.getenv('TRAC_PASS')
  45. return xmlrpclib.ServerProxy('https://%s:%s@%s' % (user, password, TRAC_XMLRPC_URL))
  46.  
  47. def _send_commit_mail(user, address, subject, branch, commits, files, diff):
  48. print 'Sending a GITRECEIVE mail to %s' % address
  49. message = 'Commits pushed to %s:\n--------------------------------------\n\n%s\n--------------------------------------\n%s\n--------------------------------------\n%s' % (branch, commits, files, diff)
  50. _send_mail(user, address, subject, message)
  51. def _send_attn_mail(user, destuser, diff):
  52. print 'Sending a "please review" mail to %s' % destuser
  53. message = '''Good day my most generous colleague! I would hold you in the highest esteem and toast you over my finest wines if you would kindly review this for me\n\n\t - %(user)s\n\nDiff:\n------------------------------------------------\n%(diff)s''' % {'diff' : diff, 'user' : user}
  54. addresses = []
  55. for d in destuser.split(','):
  56. addresses.append('%s%s' % (d, EMAIL_SUFFIX))
  57. _send_mail(user, addresses, 'Please review this change', message)
  58.  
  59. def _send_mail(user, address, subject, contents):
  60. try:
  61. if not isinstance(address, list):
  62. address = [address]
  63. s = smtplib.SMTP(MAIL_SERVER)
  64. message = 'From: %s%s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\n' % (user, MAIL_SUFFIX, ', '.join(address), subject, contents)
  65. s.sendmail('%s%s' % (user, MAIL_SUFFIX), address, message)
  66. s.quit()
  67. except:
  68. print 'Failed to send the email :('
  69.  
  70. def _update_ticket(ticket, message, options={}):
  71. rpc = rpcProxy()
  72. rpc.ticket.update(ticket, message, options)
  73. return rpc
  74.  
  75. def find_re(commit):
  76. return map(int, re.findall(r'(?i)\s+re\s*#([0-9]+)', commit))
  77. def handle_re(branch, commit, ticket):
  78. print 'Annotating ticket #%s' % ticket
  79. message = '''The following was committed in "%(branch)s":
  80. {{{
  81. %(commit)s }}}
  82. ''' % {'branch' : branch, 'commit' : commit}
  83. _update_ticket(ticket, message)
  84.  
  85. def find_qa(commit):
  86. return map(int, re.findall(r'(?i)\s+qa\s*#([0-9]+)', commit))
  87. def handle_qa(branch, commit, ticket):
  88. print 'Marking ticket #%s as "ready for QA"' % ticket
  89. message = '''The following was committed in "%(branch)s":
  90. {{{
  91. %(commit)s }}}
  92. ''' % {'branch' : branch, 'commit' : commit}
  93. rpc = _update_ticket(ticket, message, options={'status' : 'qa'})
  94.  
  95. def find_attn(commit):
  96. return re.findall(r'(?i)\s+attn\s*([A-Za-z,]+)', commit)
  97. def handle_attn(branch, commit, attn):
  98. # Unpack commit from this: "commit 5f4c31f3c31347c62d68ecb5f2c9afa3333f4ad0\nAuthor: R. Tyler Ballance <[email protected]>\nDate: Wed Nov 12 16:57:32 2008 -0800 \n\n Merge commit 'git-svn' \n\n \n \n"
  99. try:
  100. commit_hash = commit.split('\n')[0].split(' ')[1]
  101. except:
  102. return # fuk it
  103. diff = os.popen('git show --no-color %s --pretty=format:"Author: %%cn <%%ce>%%n%%s%%n%%n%%b%%n%%n%%H"' % commit_hash).read().rstrip()
  104. _send_attn_mail(getpass.getuser(), attn, diff)
  105.  
  106. def mail_push(address, oldrev, newrev, refname):
  107. user = getpass.getuser()
  108. machine = socket.gethostname()
  109. base_git_diff = 'git diff %s %s' % (oldrev, newrev)
  110. files_diffed = os.popen('%s --name-status' % (base_git_diff)).read().rstrip()
  111. full_diff = os.popen('%s -p --no-color' % (base_git_diff)).read().rstrip()
  112. ''' git rev-parse --not --branches | grep -v "$new" | git rev-list "$old".."$new" --stdin '''
  113. commits = os.popen('git rev-parse --not --branches | grep -v "%s" | git rev-list %s..%s --stdin --pretty=format:"Author: %%cn <%%ce>%%nDate: %%cd %%n%%n %%s %%n%%n %%b %%n %%n-------[post-receive marker]------%%n" --first-parent ' % (newrev, oldrev, newrev)).read().rstrip()
  114. branch = refname.split('/')[-1]
  115. mail_subject = 'GITRECEIVE [%s/%s] %s files changed' % (machine, branch, len(files_diffed.split('\n')))
  116.  
  117. if branch == 'master-release':
  118. print 'Tagging release branch'
  119. tagname = 'livepush_%s' % (time.strftime('%Y%m%d%H%M%S', time.localtime()))
  120. sys.stderr.write('Creating a tag named: %s\n\n' % tagname)
  121. os.system('git tag %s' % tagname)
  122. mail_subject = '%s (tagged: %s)' % (mail_subject, tagname)
  123.  
  124. if BUILD_HUDSON_JOB:
  125. print 'Queuing the Hudson job for "%s"' % branch
  126. os.system('/usr/bin/env wget -q -O /dev/null http://%s/job/%s/build' % (HUDSON_URL, branch))
  127.  
  128. _send_commit_mail(user, address, mail_subject, branch, commits, files_diffed, full_diff)
  129.  
  130. if branch == 'master':
  131. return # we don't want to update tickets and such for master/merges
  132.  
  133. commits = filter(lambda c: len(c), commits.split('-------[post-receive marker]------'))
  134. commits.reverse()
  135. for c in commits:
  136. if c.find('Squashed commit') >= 0:
  137. continue # Skip bullshit squashed commit
  138.  
  139. for attn in find_attn(c):
  140. handle_attn(branch, c, attn)
  141.  
  142. for ticket in find_re(c):
  143. handle_re(branch, c, ticket)
  144.  
  145. for ticket in find_qa(c):
  146. handle_qa(branch, c, ticket)
  147.  
  148.  
  149. if __name__ == '__main__':
  150. op = OptionParser()
  151. op.add_option('-m', '--mail', dest='address', help='Email address to mail git push messages to')
  152. op.add_option('-o', '--oldrev', dest='oldrev', help='Old revision we\'re pushing from')
  153. op.add_option('-n', '--newrev', dest='newrev', help='New revision we\'re pushing to')
  154. op.add_option('-r','--ref', dest='ref', help='Refname that we\'re pushing')
  155. opts, args = op.parse_args()
  156.  
  157. if not opts.address or not opts.oldrev or not opts.newrev or not opts.ref:
  158. print '*** You left out some needed parameters! ***'
  159. exit
  160.  
  161. mail_push(opts.address, opts.oldrev, opts.newrev, opts.ref)



Did you know! Slide is hiring! Looking for talented engineers to write some good Python and/or JavaScript, feel free to contact me at tyler[at]slide