Skip to content

Instantly share code, notes, and snippets.

@TimothyGillespie
Last active December 4, 2022 15:51
Show Gist options
  • Save TimothyGillespie/dd720ec748b0ded98b0032f461a1e43b to your computer and use it in GitHub Desktop.
Save TimothyGillespie/dd720ec748b0ded98b0032f461a1e43b to your computer and use it in GitHub Desktop.
Git Hook: Prepend Ticket Id From Branch Name. If other ticket IDs are prepended keep all of them.
#!/bin/bash
# Change this; if the ticket prefix and id is separated by a dash you will need to include it here
TICKET_PREFIX='TICKET-'
# Get Git branch; use grep with extended regex to capture the tickets
TICKET_IDS_BRANCH=$(git rev-parse --abbrev-ref HEAD | grep -oE "${TICKET_PREFIX}[0-9]+")
COMMIT_MESSAGE=$(cat $1)
# Extract relevant part from commit message
TICKET_IDS_COMMIT_PART=$(echo "$COMMIT_MESSAGE" | grep -oE "^((${TICKET_PREFIX}[0-9]+(, )?)+|No Ticket):")
# From that extract only the Ticket IDs
TICKET_IDS_COMMIT=$(echo "$TICKET_IDS_COMMIT_PART" | grep -oE "${TICKET_PREFIX}[0-9]+")
# Join Ticket IDs from Branch and commit message together; sort and remove duplicates; join with ", " and remove trailing commas
TICKET_IDS=$(echo -e "${TICKET_IDS_BRANCH}\n${TICKET_IDS_COMMIT}" | sort -V | uniq | tr '\n' ',' | sed 's/,$//' | sed 's/,/, /g')
# Adjust commit message to not contain any prefix
COMMIT_MESSAGE=$(echo "$COMMIT_MESSAGE" | sed "s/^$TICKET_IDS_COMMIT_PART//" | sed 's/^ //')
# When no Ticket IDs are given preface with "No Ticket"
if [ -z "$TICKET_IDS" ]; then
echo "No Ticket: $COMMIT_MESSAGE" > $1
exit 0
fi
echo "${TICKET_IDS}: ${COMMIT_MESSAGE}" > $1
@TimothyGillespie
Copy link
Author

TimothyGillespie commented Mar 7, 2022

Examples:

Branch name is feature/TICKET-1234-my-cool-feature
Commit Message: Some Commit
Result: TICKET-1234: Some Commit

Branch name is feature/TICKET-1234-my-cool-feature-and-TICKET-4321
Commit Message: Some Commit
Result: TICKET-1234: Some Commit
(only handles the first ticket ID from a branch name)

Branch name is feature/TICKET-1234-my-cool-feature
Commit Message: TICKET-4321: Some Commit
Result: TICKET-1234, TICKET-4321: Some Commit

Branch name is feature/TICKET-1234-my-cool-feature
Commit Message: TICKET-1234: Some Commit
Result: TICKET-1234: Some Commit

Branch name is feature/1234-my-cool-feature
Commit Message: Some Commit
Result: No Ticket: Some Commit

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