Skip to content

Instantly share code, notes, and snippets.

@sehraramiz
Last active July 19, 2022 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sehraramiz/7e458ac98eb2f261cd980b51367a2c15 to your computer and use it in GitHub Desktop.
Save sehraramiz/7e458ac98eb2f261cd980b51367a2c15 to your computer and use it in GitHub Desktop.
A git hook to auto add a prefix based on changed module to commit messages

file path:

  • .git/hooks/prepare-commit-msg

Add this script to .git/hooks

It looks at the staged changes in git and add a prefix to commit message based on the location of the change

If the change is in the /*/api/api_a/*.py the commit message would be:

  • "[ApiA] blah blah"

If the change is in the /*/api/api_a/.py ann /*/api/models/.py the commit message would be:

  • "[DB] [ApiA] blah blah"
:! cat .git/hooks/prepare-commit-msg
#!/bin/sh
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
A_CHANGED=$(git diff --name-only --staged | grep "/api/api_a")
B_CHANGED=$(git diff --name-only --staged | grep "/api/api_b")
MODEL_CHANGED=$(git diff --name-only --staged | grep "/app/models")
hint=$(cat "$COMMIT_MSG_FILE")
prefix=""
if [ "$MODEL_CHANGED" ] && [[ $hint != *"[DB]"* ]]
then
prefix="[DB] "
fi
if [ "$A_CHANGED" ] && [[ $hint != *"[ApiA]"* ]]
then
prefix="$prefix[ApiA]"
fi
if [ "$B_CHANGED" ] && [[ $hint != *"[ApiB]"* ]]
then
prefix="$prefix[ApiB]"
fi
echo "$prefix $hint" > "$COMMIT_MSG_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment