DEV Community

loading...

", hopefully" - An Intro to Git Hooks

brodan profile image Brodan ・2 min read

In yet another instance of a blog post inspired by a single tweet, this post will offer a very basic introduction to git hooks (commit hooks, to be specific).

I'm hooked GIF

The Tweet

I saw this on my timeline earlier today, had a good chuckle, and then realized that despite knowing about git hooks for a long time, I've never actually written one. I decided to fix that by writing a dead simple hook that would recreate the aforementioned Tweet.

The Code

Start by initializing a new git repo as such:

cd /tmp && mkdir hook-testing
cd hook-testing
git init
Enter fullscreen mode Exit fullscreen mode

git actually generates a number of sample hooks when you initialize a repo. You can see them all by running ls .git/hooks/.

If you look closely, there's a hook named prepare-commit-msg.sample. How convenient! This hook, once enabled, will run every time a git commit command is run when working in this repo.

You can read more about this hook in the githooks Documentation.

In order for git to actually pick up and run a hook, the .sample extension must be removed:

mv .git/hooks/prepare-commit-msg.sample .git/hooks/prepare-commit-msg
Enter fullscreen mode Exit fullscreen mode

Open .git/hooks/prepare-commit-msg in an editor and feel free to look at the examples. Then replace it all with the following:

#!/bin/sh
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2

DREAM=", hopefully"
if [[ "$COMMIT_SOURCE" == "message" ]]
then
    echo `cat $COMMIT_MSG_FILE`$DREAM > $COMMIT_MSG_FILE
fi
Enter fullscreen mode Exit fullscreen mode

I kept this hook pretty simple since my shell-scripting abilities are lackluster.

git passes three arguments into the prepare-commit-msg hook, but we only care about the first two:

  • $1 is the name of the file that contains the commit log message. We will append our optimistic message to this file.
  • $2 is the source of the commit message and is set according to how the commit is being generated (such as in a merge, squash, etc, or just a regular old commit).

In this case, the hook is only going to run if the commit source is "message", meaning that the commit was made using the -m flag. Feel free to modify this to your liking.

In order to see it in action, we need to commit something:

git commit --allow-empty -m "adding an empty commit"
[master 1031a40] adding an empty commit, hopefully
Enter fullscreen mode Exit fullscreen mode

As you can see above, the commit message was updated to include the ", hopefully" message. You can run git log to see it again if you want to double-check.

The Conclusion

I hope you found this post informative and entertaining. The hook itself is very simple but I actually learned a log about git internals while working on it.

If you'd like to see the other posts I've written that were inspired entirely by Tweets, consider these:

Thanks for reading!

Discussion (0)

Forem Open with the Forem app