Introduction

I had written about git hooks in an earlier post. Over the years, I have come to rely quite heavily on local commit msg hook to keep my commit messages consistent with angular commit message format.

But, it’s a pain to set up individually for every repo. I always wanted to have a single hook that could work with all my checked out repos. Since it wasn’t a huge problem, I always put it off as a someday task. Until that someday arrived last month!

My laptop needed replacement, and that meant setting up the local hooks for all the repos (which I had done gradually over the years) again.

So, I spent a few mins (or was it hours?) to skim through git docs to find a way to do this once (and for all!). Eventually, I was able to achieve what I wanted with a few steps and this script.

Steps

  1. Clone or download this repo https://github.com/abiydv/commit-msg

    $ cd ~/Downloads
    $ git clone https://github.com/abiydv/commit-msg.git
    
  2. Add a git template directory location in git config

    $ git config --global init.templatedir '~/.git/global_templates'
    
  3. Copy the downloaded commit-msg hook script to the template directory

    $ mkdir -p ~/.git/global_templates/hooks
    $ cp ~/Downloads/commit-msg/commit-msg ~/.git/global_templates/hooks/commit-msg
    
  4. Check commit-msg filesystem permissions, and make it executable.

    $ chmod +x ~/.git/global_templates/hooks/commit-msg
    
  5. Run git init for any repo which was initialized prior to adding this config.

  6. Any new repos will automatically inherit the commit-msg hook.

.. and, that’s all there is to it! 👏

Caveats

  • --template cli option or GIT_TEMPLATE_DIR env var can override the template config provided in ~/.gitconfig
  • -n or --no-verify cli option bypasses all checks.
  • Use server side hooks to enforce compliance or other checks.
  • Local hooks work with Gitbash for Windows, so no extra config is required for Windows.

Conclusion

As I mentioned in the previous post too, git local hooks can be useful to setup oversight, to make sure you don’t stray from the standards. However, they are not for setting up guardrails or enforcement as they reside on each user’s system and are completely under their control.

References (2)

  1. Commit Msg 
  2. Customizing Git Git Hooks