Git hooks
It took me a bit of tinkering to figure out how to properly write a git commit-msg hook that will run on windows. My goal was to ensure that all developers follow the commit message standard that was being developed in-house of prepending the commit message with the story number (we use Scrum so everything is a story).Our story numbers all follow a basic format, the project acronym (between 3 and 7 uppercase letters) followed by dash followed by a number. An Examples of valid story numbers are PROJ1-123, SECRET-451, etc.
Reading the documentation on customizing git hooks it quickly became obvious that we needed to write a commit-msg hook to validate the format of the commit message.
What I ended up with is the following, it was based on this blog post by Phillip Murphy.
#!/bin/sh
commit_regex='^[A-Z]\{3,6\}-[0-9]\{1,10\} .*'
echo $1
error_msg="Aborting commit. Your commit message MUST start with the story number followed by a space."
if [[ "$(grep "$commit_regex" $1)" == "" ]]; then
echo "$error_msg" >&2
exit 1
fi
Copy that script into a file in named commit-msg in .git\hooks. Note: the file has no extension.
The interesting pieces of developing this are that since it is shell script, the only way to test it was to install the hook and then try to do a commit to git. I am not completely certain what is executing the shell script as I have nothing on my Windows 10 box that I am aware of that will do it, it seem that git for windows may be executing the shell script???
As far as the syntax the regex expression was interesting I wanted to use [0-9]+ but that wouldn't work, it produced a syntax error so instead we are using {<min occurrence>,<max occurrence>} with the curly braces escaped with a backslash.
The other item that I found interesting was the use of grep to do a regex match. It works in this case because $1 is the file that contains the commit message. the commit message is written to .git/COMMIT_EDITMSG, you can verify this by adding echo $1 to the script
The next challenge is to get this installed on every developers computer in every copy of the repo. There are a number of answers, but the best for us seems to be the use of a template directory since this will be mandatory for all commits
A future enhancements is to validate that the story number that is found is actually a valid story number, this will help ensure no one fat fingered it on entry.
As a last interesting side note, now that we know how to do this, we have decided for now that it is overkill for what we want to accomplish so all that is left of this mornings work is this post.
No comments:
Post a Comment