Follow these steps to configure a global Git hooks directory and set up a prepare-commit-msg
hook that appends diffs to commit messages.
- Create a directory
~/.git/hooks
to store your global hooks.mkdir -p ~/.git/hooks
- Configure Git to use
~/.git/hooks
as the global hooks directory.git config --global core.hooksPath ~/.git/hooks
- Create the
commit-msg
hook file and make it executable.touch ~/.git/hooks/commit-msg chmod +x ~/.git/hooks/commit-msg
- Edit and add the following to the file.
#!/bin/bash # The commit message file COMMIT_MSG_FILE="$1" # Remove lines starting with # sed -i '/^#/d' "$COMMIT_MSG_FILE" exit 0
- Create the
prepare-commit-msg
hook file and make it executable.touch ~/.git/hooks/prepare-commit-msg chmod +x ~/.git/hooks/prepare-commit-msg
- Edit the
prepare-commit-msg
file and add the following script:#!/bin/sh # The first argument is the path to the commit message file commit_msg_file="$1" commit_source="$2" # The second argument indicates the source (e.g., commit, merge, cherry-pick) # Exit if a rebase is in progress if [ -d "$(git rev-parse --git-dir)/rebase-merge" ] || [ -d "$(git rev-parse --git-dir)/rebase-apply" ]; then exit 0 fi # Exit if this is a cherry-pick if [ -f "$(git rev-parse --git-dir)/CHERRY_PICK_HEAD" ]; then exit 0 fi # Append the diff to the commit message file as comments without overriding the existing message git diff --cached | sed 's/^/# /' >> "$commit_msg_file"
To verify that your global hook is working:
-
Stage some changes:
git add <your-files>
-
Commit the changes:
git commit
When the commit message editor opens, you should see the default commit message template followed by the diff of the staged changes commented out at the bottom.