Skip to content

Instantly share code, notes, and snippets.

@jack-webb
Last active October 1, 2022 15:47
Show Gist options
  • Save jack-webb/837f13f4678b4431ba5b9bea99c2d6fa to your computer and use it in GitHub Desktop.
Save jack-webb/837f13f4678b4431ba5b9bea99c2d6fa to your computer and use it in GitHub Desktop.
Prepend the branch name to your commit message automatically
#!/bin/bash
# Produces output like "[my-branch] My Commit" or "[TICKET] Add foo and bar"
# Use "BRANCHES_TO_SKIP" if you don't want to prepend
# the branch name onto commits on a certain branch
if [ -z "$BRANCHES_TO_SKIP" ]; then
 BRANCHES_TO_SKIP=(main develop my-special-branch)
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
 sed -i.bak -e "1s/^/$BRANCH_NAME /" $1
fi
# This script is widely shared online, so I couldn't find the original author
# There are lots of variants, so if you need some extra logic, take a look!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment