Skip to content

Instantly share code, notes, and snippets.

@franksteinberg
Forked from bartoszmajsak/prepare-commit-msg.sh
Last active July 16, 2020 01:35
Show Gist options
  • Save franksteinberg/8dff00204255154ab8190d6974db914e to your computer and use it in GitHub Desktop.
Save franksteinberg/8dff00204255154ab8190d6974db914e to your computer and use it in GitHub Desktop.
How to automatically prepend git commit with a branch name
#!/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)
AFTER_FIRST_SLASH=$(echo "${BRANCH_NAME#*/}")
TICKET=$(echo "${AFTER_FIRST_SLASH%%/*}")
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$TICKET$")
BRANCH_IN_COMMIT=$(grep -c "\[$TICKET\]" $1)
if [ -n "$TICKET" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s/^/[$TICKET] /" $1
fi
@franksteinberg
Copy link
Author

franksteinberg commented Sep 6, 2019

Rename .git/hooks/prepare-commit-msg.sample to prepare-commit-msg, paste the script and make the file executable.

For instance with branch ARQ-653
$ git commit -m"Fixed bug"
will result with commit "[ARQ-653] Fixed bug"

Script handles branching name which is for example used in git-flow. Eg for branch 'feature/ABC-399' it will extract ABC-399

More elaborated way with the reasoning behind this can be found on my old and dusty blog http://blog.bartoszmajsak.com/blog/2012/11/07/lazy-developers-toolbox-number-1-prepend-git-commit-messages/

UPDATE: The script now handles multiple forward slashes in the branch name. The "ticket number" will be whatever is after the first slash in the branch, ending at the next slash or end of the string, whichever comes first.

Examples:

branch name commit prefix
ARQ-123 [ARQ-123]
feature/ARQ-123 [ARQ-123]
feature/ARQ-123/add-login-form [ARQ-123]

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