Pliant AllianceSoftware development notes & tools

Enforcing commit policies with Subversion hooks

Subversion keeps an excellent record of what changed, but it has no opinion about whether a change should have happened. A revision can arrive carrying a debugging print left behind in a servlet, a compiled class file dropped into a source tree, a password pasted into a properties file, or a log message that reads only “fixed”. Leaving these judgements to a human reviewer means the rule survives exactly as long as somebody remembers to apply it.

Automation at the repository is the alternative. Hook scripts run on the server, at fixed moments in the life of a commit, and they apply the same verdict to every working copy, every developer and every operating system. That matters for teams spread across Australian cities, where a morning commit from a laptop on a Sydney train must meet the same standard as one made at a desk in a Melbourne office or a home study in Brisbane.

The mechanics are simple enough to learn in an afternoon, and fiddly enough to reward careful reading. A hook is a small program invoked by the version control server; the arguments it receives, the way it signals rejection, and the point in the transaction at which it runs all determine whether your policy is enforceable or merely advisory. This article works through the practical side of that machinery: where the scripts live, what they can inspect, and how to keep them honest.

What a commit policy actually says

A commit policy is a written statement about acceptable changes to the repository. It is worth writing that statement down before writing any code, because a hook that enforces a rule nobody articulated will eventually be resented. Most useful policies fall into a few layers: file hygiene, message and metadata conventions, workflow rules about branching and merging, and security restrictions on sensitive material.

Examples are easy to invent and easy to overreach. “No compiled artefacts under trunk” is clear and testable. “Every commit should be well written” is neither, and a hook that tries to judge prose will be ignored or disabled. The same goes for blanket rules about which files a developer may touch: a policy that names one protected directory, or one class of credential file, is defensible. A policy that forbids every modification outside a single branch will simply be worked around.

The test for a good rule is that a competent developer can understand it before their first commit and can satisfy it without asking permission. For a small team, three or four rules of that quality are worth more than twenty aspirational ones.

Where hooks live and when they run

A Subversion repository created with svnadmin create contains a hooks directory with sample scripts already sitting in it. The names that matter are pre-commit, post-commit, start-commit, pre-revprop-change and post-revprop-change. When the same repository is served through Apache with mod_dav_svn, the scripts are not read from the repository directory; the server is pointed at a separate configuration directory with the --config-dir option, typically somewhere like /usr/local/apache2/conf/svn, and that directory holds its own hooks folder. A standalone svnserve instance takes a similar option. This is the first trap: a perfectly good script in the wrong directory never runs, and nobody notices until policy enforcement is missed.

The sequence within a commit is short. start-commit runs on the client, before anything is sent, and is mostly used for authentication. pre-commit runs on the server with the repository path and a transaction name, and can inspect the proposed change before it becomes a revision. If it exits with a non-zero status, the transaction is discarded and the client is told why. post-commit runs after the revision number has been assigned, and receives the repository path and the new revision number. The two revprop hooks cover the rarer case of editing revision properties, such as the commit log or author, after the fact.

The distinction between a transaction and a revision is more than pedantry. Inside pre-commit you inspect a pending transaction that may be abandoned, so the tools you use are svnlook author, svnlook changed, svnlook files and svnlook info with the -t option. Inside post-commit you work with a permanent revision, so svnlook commands take -r and the commit has already entered history. Scripts written for one context and dropped into the other will fail in confusing ways.

Writing a pre-commit hook that blocks bad revisions

The workhorse policy is a pre-commit script that examines changed paths and refuses the transaction. A workable version for a Unix server looks like this:

#!/bin/sh
REPOS="$1"
TXN="$2"

PATHS=$(svnlook changed "$REPOS" -t "$TXN" | sed 's/^[ADUR] *//')

for P in $PATHS
do
  case "$P" in
    */secrets/*|*.pem|*.key|*/local.properties)
      echo "Rejected: $P looks like credential material." >&2
      exit 1
      ;;
    *.class|*.pyc|*/build/*)
      echo "Rejected: $P is generated output." >&2
      exit 1
      ;;
  esac
done

LOG=$(svnlook info "$REPOS" -t "$TXN")
case "$LOG" in
  *"[A-Z][A-Z][A-Z]-[0-9][0-9][0-9]"*) ;;
  *)
    echo "Rejected: the log message needs an issue key such as PLI-104." >&2
    exit 1
    ;;
esac

exit 0

Two details make or break this. The script needs the executable bit set, and it must be owned and readable by the account the server runs as; a hook that cannot be executed is silently skipped. The second detail is that the rejection message is the user interface of the policy, so it should name the offending path and the rule, rather than muttering about a violation. A developer who sees Rejected: /trunk/config/local.properties looks like credential material knows exactly what to do. A developer who sees commit failed learns nothing and will try again with the file still in place.

Keep the checks fast and the failure list short. Every svnlook call reads the repository, so a script that scans the whole tree on each commit will eventually be blamed for sluggishness. Where a rule concerns binary content, inspect the svn:mime-type property instead of guessing from the file extension, since a renamed .txt still carries its original property. Test the script against a scratch repository rather than the working one; a policy hook is exactly the sort of code that benefits from being reviewed by someone other than its author.

Log messages, properties and traceability

Log messages are the cheapest thing to police and the most useful thing to store. A convention such as PLI-104: fix rounding in invoice total gives every revision a key that points at a ticket, supports release notes assembled with svn log, and lets a later auditor reconstruct the reason for a change. Enforcing the convention is a two-line check inside pre-commit, as shown above, and the pattern is a decision your team should make once and write down.

Properties do the quiet work. svn:auto-props can set svn:eol-style, svn:keywords and svn:mime-type on every new file, which removes an entire category of noisy diffs when a Windows laptop and an Ubuntu desktop share a project. The pre-revprop-change hook guards a subtler problem: revision properties can be rewritten after the fact by an administrator, including the log message and the recorded author. On a repository that feeds an audit trail, that is a hole worth closing, and the hook can compare the old and new values before allowing the edit.

A post-commit hook is the natural place to turn a revision into a notification. It can append a line to a changelog, mail a short summary to a distribution list, or poke a build daemon. Each of those uses the new revision number, so the message can quote the exact diff with svn diff -c REV and reference the issue key parsed from the log.

Branches, merges and review before history

Most repositories of this vintage organise history into trunk, branches and tags. A commit policy usually wants to say something about movement between them: releases are cut on a branch, hot fixes are merged forward, and trunk moves steadily. Hooks can help, though they cannot read intent. A script can demand that a commit touching a release branch carries an issue key and a particular word in the log; it cannot tell whether the author intended a fix or a mistake.

Review policy belongs in the same conversation. Where a team practises pair programming, the second pair provides the review, and the commit message can record it. Where the team is distributed, a common approach of the period was to commit first and review afterwards from the svn diff output, with a Reviewed-by: line in the log message added as a second revision property change. A pre-commit hook can require that line, which moves the review marker into the history where a release manager can find it. Either way, the useful convention is the same: state in the log who reviewed the change and against which ticket.

This is also where the log message earns its keep. A month later, when a strange line in a release appears, the trail runs from the branch, to the revision, to the issue, to the reviewer. Without the marker, the trail stops at a name and a date.

Keeping the rules identical across servers

A policy that lives on one developer’s machine is a suggestion. The durable arrangement is to keep the canonical hook script in a separate repository, versioned like any other code, and deploy it to every Subversion server the organisation runs. Changes to the policy then arrive through the same review path as changes to the application, and the commit that tightens a rule carries its own history.

Portability is the recurring headache. Servers in this era were a mixture of Linux boxes running Apache and mod_dav_svn, dedicated svnserve instances, and Windows machines where a small team installed Subversion from the official package and served it locally. A hook written with Bash arrays, GNU-only flags or Unix line endings will fail on the Windows host in ways that are tedious to diagnose. #!/bin/sh, POSIX tools, quoted paths and a deliberate choice about line endings travel better, and where a Windows-native implementation is unavoidable, keeping the two versions in step becomes an administrative task in itself.

Everyday Australian work habits strengthen the case for central enforcement. Plenty of developers commit from a café with wireless in a Melbourne laneway, from a home office in Adelaide, or from a laptop on a train between Sydney and the outer suburbs, and a client-side check is only as reliable as the client that ran it. The server-side hook does not care. It applies to the developer on the train, the consultant in Perth, and the contractor with a freshly cloned working copy.

Audit trails and the local regulatory floor

Australian organisations that answer to government clients, financial institutions or large corporate customers are often asked to demonstrate who changed what, and when, and under whose authority. The Privacy Act 1988 (Cth) and its privacy principles, the protective security guidance published for government systems, and the audit requirements common to banks and telcos all push in the same direction: the revision history needs to be attributable and difficult to rewrite. svnlook author gives the account name attached to the commit, revision properties record the same identity on the revision itself, and a locked-down pre-revprop-change hook prevents casual edits to the log. Canberra agencies and the defence and intelligence community have long made this kind of accountability routine.

Automated notifications carry their own local constraint. The Spam Act 2003 applies to commercial electronic messages sent in bulk, so a post-commit hook that mails a build failure to a distribution list should identify its sender clearly and remain within transactional mail that recipients would reasonably expect, or honour an opt-out if the content is closer to marketing.

The local software market makes the exercise concrete. Atlassian, founded in Sydney, built its early products for small development teams and went on to reshape how Australian teams track issues, which is exactly the pairing a hook policy depends on: an issue key in the repository, a ticket in the tracker, both written in the same vocabulary. Meanwhile banks, insurers and telecommunications firms in Sydney and Melbourne, consultancies in Brisbane and Perth, and small product houses running Subversion on an Ubuntu workstation all inherit the same need. Some inherited it by choice, some because a client’s audit required a record they could show.

A commit policy enforced by hooks is best understood as a piece of shared infrastructure: written down, stored in version control, tested against a scratch repository, and amended through the same careful review as any other change. Once it lives in the repository, it stops being a habit the team must maintain and becomes an agreement the team keeps.