Last active
September 27, 2023 11:28
-
-
Save a-c-m/d909bcfe939144f66854c9d60b83b5da to your computer and use it in GitHub Desktop.
git/hooks/prepare-commit-msg (auto prefix ticketID)
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 | |
# Idea is mine (@a_c_m), code it ChatGPT-4, don't forget to `chmod +x .git/hooks/prepare-commit-msg` | |
# Automatically adds the ticket ID to the commit message, or warns how to do it. | |
# Get the current branch name | |
BRANCH_NAME=$(git symbolic-ref --short HEAD) | |
# Parse arguments | |
COMMIT_MSG_FILE="$1" | |
COMMIT_SOURCE="$2" | |
SHA1="$3" | |
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE") | |
# Check if commit message starts with a ticket ID | |
if ! [[ "$COMMIT_MSG" =~ ^[A-Z]+-[0-9]+ ]]; then | |
# If not, check if branch name starts with a ticket ID | |
if [[ "$BRANCH_NAME" =~ ^[A-Z]+-[0-9]+ ]]; then | |
# If yes, extract the ticket ID and prefix it to the commit message | |
TICKET_ID=$(echo "$BRANCH_NAME" | grep -o '^[A-Z]\+-[0-9]') | |
COMMIT_MSG="$TICKET_ID: $COMMIT_MSG" | |
else | |
# If not, print a warning and instructions to amend the commit message | |
echo "WARNING: Commit message does not start with a ticket ID (e.g. 'TEST-123: ')." | |
echo "You can re-commit to amend your commit message, use: git commit --amend -m 'TEST-123: old message'" | |
fi | |
fi | |
# Write the possibly modified commit message back to the file. | |
echo "$COMMIT_MSG" > "$COMMIT_MSG_FILE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment