In my last post I showed how to build a simple hooking system for sitaramc/gitolite Now I just want to share a very small script used to update Redmine changesets when you push to a git repository.

Background.

Redmine has an excellent repository viewer built in. It is even capable of reading through commit messages and closing tickets based on the contents, a very useful feature that we are taking advantage of. Due to this, having a team member commit a bug fix can fire off an email to the person who originally created the bug ticket, or at least it should.

The problem.

By default Redmine only processes these repositories when you visit the repository tab in a project. This makes sense, how else is it supposed to know when you've actually updated the repository? The most common solution to the problem is to set up cron to run a task to tell Redmine to update all repositories. Excellent, we can use this in a hook and make it all on demand and avoid wasting precious cycles ;)

The solution.

We can use a hook to only process repository updates when the repository is.. updated.

Before we do this it's a good idea to disable commit fetching in Redmine. This can be done by navigating to Administraion -> Settings -> Repositories and unchecking Fetch commits automatically, followed by a save.

Edit: While you're there, go ahead and check "Enable WS for repository management" and generate an API key. Make sure to write this down.

Once this is done we can add the Gitolite hook. This lives under local-code/hooks/common/hooks.d/ in your gitolite-admin repository.

update-redmine-repositories (updated, using web service)

#!/bin/bash
read oldrev newrev refname

# This can be generated in the admin page, make sure to enable the WS.
REDMINE_KEY='yourrepositorymanagementwskeyhere'

# Quickly do a lookup of our working directory and see which project it belongs to.
# If your repository names are consistent with Redmine then you might be able to use
# an alternative method to get the PROJECT_ID from current path.
PROJECT_ID=$(mysql -r -u redmineuser -predminepassword redminedb -e "select project_id from repositories where url = '$PWD';")

# Do the update.
curl -s http://yourredmineurl/sys/fetch_changesets?key=$REDMINE_KEY&id=$PROJECT_ID

Edit: Below is the original script, which will update ALL repositories (and therefore is a little slower).

update-redmine-repositories (original, refresh everything)

#!/bin/bash
read oldrev newrev refname

REDMINE_DIR=/home/redmine/redmine/

# Assuming you're using RVM for Ruby management.
# Make sure that VER is replaced with the correct version.
RVM_ENVIRONMENT_PATH=/home/redmine/.rvm/environments/ruby-VER
source $RVM_ENVIRONMENT_PATH

# This line here is the magic.
$REDMINE_DIR/script/rails runner "Repository.fetch_changesets" -e production > /dev/null 2>&1 &

Make the file executable and all that's left from here is to enable the hook on your Gitolite repositories.