Skip to content

Instantly share code, notes, and snippets.

@chandra-prakash-meghwal
Last active January 10, 2023 04:38
Show Gist options
  • Save chandra-prakash-meghwal/59fe4a6b4f2541b2f6bb47d293cce83a to your computer and use it in GitHub Desktop.
Save chandra-prakash-meghwal/59fe4a6b4f2541b2f6bb47d293cce83a to your computer and use it in GitHub Desktop.
Automatically add git branch name to the commit message. Add the below file to .git/hooks/ directory and make it executable with the command $ chmod +x prepare-commit-msg, the below code excludes branch names master develop test
#!/bin/bash
# This way you can customize which branches should be skipped when
# prepending commit message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop test)
fi
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
# to add branch at the end of the commit message
sed -i.bak -e "1s/$/[$BRANCH_NAME] /" $1
# # to prepend branch name to the commit message, use ^ instead in regular expression
# sed -i.bak -e "1s/^/[$BRANCH_NAME] /" $1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment