Last active
January 19, 2024 20:31
-
-
Save willwfsp/9ad2363a3482a69efe67fb569c369883 to your computer and use it in GitHub Desktop.
Add Jira ticket to commit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Automatically adds branch name and branch description to every commit message. | |
# Modified from the gist here https://gist.github.com/bartoszmajsak/1396344 | |
# | |
# This way you can customize which branches should be skipped when | |
# prepending commit message. | |
if [ -z "$BRANCHES_TO_SKIP" ]; then | |
declare -a BRANCHES_TO_SKIP=(master staging develop) | |
fi | |
if [ -z "$GIT_DIR" ]; then | |
GIT_DIR=.git | |
fi | |
# Will find a ticket number anywhere in a string. | |
TICKET_ANYWHERE_REGEX="([A-Z]+-\d+)" | |
# Will find the ticket number at the beginning of a string only. | |
# Tests https://regex101.com/r/InYZZV/2 | |
TICKET_AT_START_ONLY_REGEX="^$TICKET_ANYWHERE_REGEX" | |
# Get entire branch name | |
BRANCH_NAME=$(git branch | grep '*' | sed 's/* //') | |
# Branch name should be excluded from the prepend | |
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep --count "^$BRANCH_NAME$") | |
# Gets a ticket number already at the start of the commit message (if it is present) | |
TICKET_AT_START_OF_COMMIT_MSG=$(grep --extended-regexp --only-matching $TICKET_AT_START_ONLY_REGEX $GIT_DIR/COMMIT_EDITMSG) | |
# Prefix should contain a valid ticket format | |
IS_COMMIT_BRANCH_VALID=$(echo "$TICKET_AT_START_OF_COMMIT_MSG" | grep --extended-regexp --count "$TICKET_ANYWHERE_REGEX$") | |
BRANCH_VALID_PREFIX=$(echo "$BRANCH_NAME" | grep --extended-regexp --only-matching $TICKET_ANYWHERE_REGEX) | |
if [[ -n $TICKET_AT_START_OF_COMMIT_MSG ]] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && [[ $IS_COMMIT_BRANCH_VALID -le 0 ]]; then | |
echo "Check your ticket number." | |
exit 1 | |
fi | |
if ! [[ -n $BRANCH_VALID_PREFIX ]] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && [[ $IS_COMMIT_BRANCH_VALID -eq 0 ]]; then | |
echo "Check your branch name or commit with a valid ticket number." | |
exit 1 | |
fi | |
if [[ -n "$BRANCH_VALID_PREFIX" ]] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ -n $TICKET_AT_START_OF_COMMIT_MSG ]]; then | |
sed -i.bak -e "1s/^/$BRANCH_VALID_PREFIX: /" "$GIT_DIR/COMMIT_EDITMSG" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment