Most of my company projects have a requirement that we run clang-format on all commits to keep a consistent style. Unfortunately, I’m as forgetful as the fabled goldfish (which actually isn’t that forgetful it turns out) so I often forget to run clang-format.
After the umpteenth time of forgetting and suffering some quite deepseated rage from my colleagues, I decided to investigate a way to automate the process.
It turns out git has a really cool feature introduced in 1.7.0 to specify a folder of hooks, such that when you run git clone or git init to create a new local copy of a repository, it will as part of the creation process take a copy of these ‘template’ git hooks and use them in the repository.
I’ve created a GitHub repo git-hooks that contains my pre-commit hook for running clang-format on all .c, .cpp, .cc and .h files before committing them.
To use, simply clone the git repo to a folder <whatever folder name you choose>, and then run;
git config --global init.templatedir "<whatever folder name you choose>"
Then whenever you clone or init a git repository this hook will be copied and be used in your repositories. If you have existing repositories that you want to use the hook, simply re-run git init in the repository and it will copy the hook across.
One minor caveat, if you have any pre-existing git pre-commit hook in the repository then git will not overwrite it.
I’ve tested this on Windows and Linux, and I hope it proves as useful to others as it has been to me!