Automate your git workflow with hooks, part #1
At MeilleursAgents, we follow the GitFlow principles to create “features” or “fixes” branches. We also have a set of guidelines for using git
in a frictionless way, and one of them is to prepend every commit message with the JIRA's identifier, in the form of [PROJECT]-[NUMBER]
.
In order to fullfil this guideline in a seamless manner, we wrote a prepare-commit-msg
that handles it automagically if the branch's name respects a given pattern.
#!/usr/bin/env bashBRANCH_NAME=`git symbolic-ref --short HEAD`if [[ -n "${BRANCH_NAME}" && "${BRANCH_NAME}" =~ (features|fixes)/([A-Z]+[-_][0-9A-Z]+) ]]; then PREFIX="${BASH_REMATCH[${#BASH_REMATCH[@]}-1]}"
if [[ ! `cat ${1}` =~ ^${PREFIX} ]]; then
sed -i.bak -e "1s/^/$PREFIX /" "${1}"
fifi
Then, you can simply commit (or amend) your work, it will be prepended only once.
$ git commit -m "Adding features"
[features/TECH-XXX_medium 41dd02b] TECH-XXX Adding feature
Git hooks are quite hard to manage as every contributor has to set and maintain them individually. Like a Jenkinsfile or others Infrastructure as code patterns, versioning the hooks and putting them in the repository is the best way to keep them up-to-date. We tackle this complexity with the help of symlinks.
With the given folder structure somewhere in a repo…
├── hooks
│ ├── pre-commit
│ └── prepare-commit-msg
└── install_hooks.sh
…and the install_hooks.sh
that contains every automation you need...
#!/usr/bin/env bashWORKING_DIR=`pwd`
HOOKS_DIR="hooks"
GIT_ROOT=`git rev-parse --show-cdup`for file in `ls ${HOOKS_DIR}`; do
fullpath="${WORKING_DIR}/${GIT_ROOT%%/}/.git/hooks/${file}" if [ -L "${fullpath}" ]; then
rm -f "${fullpath}"
fi ln -s "${WORKING_DIR}/${HOOKS_DIR}/${file}" "${fullpath}"
echo "${file} hook installed"
done
…every contributor must run install_hooks.sh
once to be set up!