Subversion Commit Emails on Windows Using Python

Setting up subversion commit emails using python on Windows.

First things first – you’ll need subversion and python installed.

Subversion hooks are setup by dropping an executable in the /repositoryPath/hooks/ directory. On Windows this executable needs to be either a .BAT or .CMD file. From this script you can call your python code to perform any processing. One gotcha on Windows is the $PATH environment variable is not passed so you’ll need to set this up in your cmd/bat file.

My post-commit.cmd file looks like this:

@echo off set REPOS=%1 set REV=%2 set PATH=c:\python31; python.exe d:\repositories\reponame\hooks\processCommit.py %REPOS% %REV%

The post-commit hook gets sent two variables from svn – the repository and the revision. I save those, set the path, and call processCommit.py.

processCommit.py

import smtplib, subprocess, sys import email.utils from email.mime.text import MIMEText repo = sys.argv[1] rev = sys.argv[2] repository = 'This_is_the_name_in_the_email' sender = 'subversion@emailserver.com'                     # Change to any email address receivers = ['recp1@your.com', 'recp2@your.com']          # List of email recipients # Get subversion information # 'svnlook changed' returns what files / paths have changed # 'svnlook info' returns author, date/time, log message cmd = 'c:\\program files\\Path to SVN\\bin\\svnlook changed %s -r %s' % (repo, rev) changed = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] cmd = 'c:\\program files\\Path to SVN\\bin\\svnlook info %s -r %s' % (repo, rev) commitMsg = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] message = """A commit has been made to the %s repository *** Commit Information *** """ % (repository) message = message + commitMsg.decode('utf-8') + '\n*** Changed Files ****\n\n' + changed.decode('utf-8') msg = MIMEText(message) msg['To'] = ', '.join(receivers)          # Generate string containing recpts. comma separated. msg['From'] = email.utils.formataddr(('Subversion', 'subversion@emailserver.com')) msg['Subject'] = 'Subversion Commit | %s' % (repository) try:         session=smtplib.SMTP('SMTPSERVER')      # Your SMTP Server         session.sendmail(sender, receivers, msg.as_string())         print('Notification of commit sent') except SMTPException:         print('Unable to send notification')

svnlook is your friend when writing svn hooks. The core of processCommit.py is using svnlook to retrieve information about what was changed and who changed it. The rest of the code is straigh-forward, basic python. After the information is retrieved from svn, the message is formatted, and sent on it’s way using email.

Leave a comment