Last active
April 2, 2025 20:26
-
-
Save mt89vein/ee1d87c8101fb29350ce2be2b1e6cf15 to your computer and use it in GitHub Desktop.
prepare-commit-msg git hook, that adds jira ticket number to commit scope
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/sh | |
| . "$(dirname "$0")/_/husky.sh" | |
| # path to file with commit message | |
| COMMIT_MSG_FILE=$1 | |
| # take current branch name | |
| BRANCH_NAME=$(git symbolic-ref --short HEAD) | |
| if [ $? -ne 0 ] || [ -z "$BRANCH_NAME" ]; then | |
| exit 0 | |
| fi | |
| # parse ticket name in Jira format. e.g. SSTV-123, where SSTV is project the name. | |
| TICKET_NAME=$(echo $BRANCH_NAME | { grep -Poi '[A-Z]+-[0-9]+' || true; }) | |
| # if there no ticket name in branch name - exit | |
| if [ -z "$TICKET_NAME" ]; then | |
| exit 0 | |
| fi | |
| ORIGINAL_MSG=$(cat "$COMMIT_MSG_FILE") | |
| # if developer already added ticket number to the scope, job done. | |
| if echo "$ORIGINAL_MSG" | grep '^[a-z][a-z]*([A-Za-z0-9][A-Za-z0-9-]*):' >/dev/null; then | |
| exit 0 | |
| fi | |
| # Take commit type. Everything before first colon. | |
| COMMIT_TYPE=$(echo "$ORIGINAL_MSG" | sed 's/^\([a-z][a-z]*\).*/\1/;t;d') | |
| # commit type not found, exit | |
| if [ -z "$COMMIT_TYPE" ]; then | |
| exit 0 | |
| else | |
| # add ticket name to commit message. e.g. fix: something -> fix(SSTV-123): something | |
| NEW_MSG=$(echo "$ORIGINAL_MSG" | sed "s/^$COMMIT_TYPE/$COMMIT_TYPE($TICKET_NAME)/") | |
| echo "$NEW_MSG" > "$COMMIT_MSG_FILE" | |
| fi | |
| exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment