Skip to content

Instantly share code, notes, and snippets.

@davidecaruso
Last active November 16, 2023 10:58
Show Gist options
  • Save davidecaruso/fa3aa55742590aa177886b9a7d853f49 to your computer and use it in GitHub Desktop.
Save davidecaruso/fa3aa55742590aa177886b9a7d853f49 to your computer and use it in GitHub Desktop.
Git hook to prefix commit with Jira ticket
#!/bin/bash
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [ -n "$BRANCH_NAME" ] && [ "$BRANCH_NAME" != "HEAD" ] && [ "$SKIP_PREPARE_COMMIT_MSG" != 1 ]; then
PREFIX_PATTERN='[A-Z]{2,}\-[0-9]{2,}'
[[ $BRANCH_NAME =~ $PREFIX_PATTERN ]]
PREFIX=${BASH_REMATCH[0]}
PREFIX_IN_COMMIT=$(grep -c "^$PREFIX\:" "$1")
if [[ -n "$PREFIX" ]] && ! [[ $PREFIX_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s~^~$PREFIX: ~" "$1"
fi
fi
@davidecaruso
Copy link
Author

An alternative may be:

#!/bin/bash
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"

BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)

regex="(^[a-zA-Z]{3,4}-[0-9]{1,4})"

[[ $BRANCH_NAME =~ $regex ]]

BRANCH_PREFIX=${BASH_REMATCH[1]}

if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
    sed -i.bak -e "1s/^/$BRANCH_PREFIX: /" $1
fi

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