Skip to content

Instantly share code, notes, and snippets.

@devdrops
Created October 5, 2016 21:54
Show Gist options
  • Save devdrops/7a77472d8ee3e4be2df2569f9a66dfe5 to your computer and use it in GitHub Desktop.
Save devdrops/7a77472d8ee3e4be2df2569f9a66dfe5 to your computer and use it in GitHub Desktop.
Git hook to include the branch name on each commit

Git hook to include the branch name on each commit

Tired to forget to write every goddam time the branch name on the commit messsage? This got you covered:

  1. Add the prepare-commit-msg file to your .git/hooks/ folder;
  2. Then, chmod +x prepare-commit-msg;
  3. PROFIT!
#!/bin/bash
BRANCHNAME=$(git branch | grep '*' | sed 's/* //')
if [ -n "$BRANCHNAME" ]
then
echo "" >> "$1"
echo $BRANCHNAME >> "$1"
fi
@devdrops
Copy link
Author

devdrops commented Nov 9, 2022

Improved version

Requires git config commit.status = false. Also, works best with templates 😉

#!/bin/bash
#
##################################
# GIT PREPARE COMMIT MESSAGE HOOK
#
# References:
#   - https://gist.github.com/devdrops/7a77472d8ee3e4be2df2569f9a66dfe5
##################################

BRANCHNAME=$(git branch | grep '*' | sed 's/* //')

# Extra info to add the current branch name in the commit message
if [ -n "$BRANCHNAME" ]
then
    echo "" >> "$1"
    printf "================> EXTRAS <================\n" >> "$1"
    printf "> Branch name:\t${BRANCHNAME}\n" >> "$1"
fi

# Everything written below these lines will be ignored
printf "\n# ------------------------ >8 ------------------------" >> "$1"
printf "\n# Do not modify or remove the line above." >> "$1"
printf "\n# Everything below it will be ignored." >> "$1"

# List all changes, in a nutshell
GITDIFF=$(git diff --name-status -r)
printf "\n\nChanges introduced:\n\n${GITDIFF}" >> "$1"

# Details of all changes
GITDIFFVERBOSE=$(git diff -v)
printf "\n\n${GITDIFFVERBOSE}" >> "$1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment