Last Updated: February 25, 2016
·
1.729K
· helmedeiros

Agile traceability in each git commit with Hooks

Like many other Version Control Systems, [Git](http://en.wikipedia.org/wiki/Git_(software\)) has a way to fire off custom scripts when certain important actions occur, called of hooks, they can be used in operations such as committing and merging.

There were some hooks that I've always love to have running no matter what git repository I'm commiting, like:

  • Spell check the commit message;
  • Verify that the project still builds;
  • Verify that the business rules are being maintained with my test suite;
  • Standardize my commit messages according to rules/standards;
  • Verify that any new code follows the 'standard' coding style.

Saying that, is important to discover how to apply some hooks, so we can extract the best of our Version Control flow.

The hooks are all stored in the hooks subdirectory of the Git directory. In most projects, that’s .git/hooks. You can write them in Shell Script, [Ruby](http://en.wikipedia.org/wiki/Ruby_(programming_language\)), [Python](http://en.wikipedia.org/wiki/Python_(programming_language\)) or what have you.

Standardize my commit messages according to rules/standards;

To set 'standard' messages prefix or suffix into your commits, making possible an "agile traceability" like pattern, we'll need to work with the prepare-commit-msg hook.

The prepare-commit-msg hook runs before the commit message editor is fired up but after the default message is created. It lets you edit the default message before the commit author sees it. This hook takes a few options: the path to the file that holds the commit message so far, the type of commit, and the commit SHA-1 if this is an amended commit.

Create default values:

To make it simpler the recurrent update need from the progression of yours sprints and releases, let's keep three git configurations into global scope.

$git config --global team.name "Paynews"
$git config --global team.release "R12"
$git config --global team.sprint "S5"

Add a new hook:

To enable a hook script, we'll put a file in the hooks subdirectory with the proper hook name (prepare-commit-msg).

$ mv .git/hooks/prepare-commit-msg.sample .git/hooks/prepare-commit-msg
$ vi ~/.git/hooks/prepare-commit-msg    
#!/bin/sh
#
# hook for Traceability 

TEAM=$(git config --global team.name)
SPRINT=$(git config --global team.sprint)
RELEASE=$(git config --global team.release)

if [ -n "$TEAM" ] && [ -n "$SPRINT" ] && [ -n "$RELEASE" ]; then
    sed -i.bak -e "1s/^/[$RELEASE-$SPRINT][$TEAM] /" $1
fi

Save it! And don't forget to make it executable

$ chmod +x .git/hooks/prepare-commit-msg

DONE!! AFTER COMMIT!!

Picture

Thanks for:
João Feck
Rafael Pereira

1 Response
Add your response

Nice post! Wasn't aware of this functionality. I've always done it the other way around, i,.e. a script that does the stuff I want then calls git commands.

over 1 year ago ·