Skip to content

Instantly share code, notes, and snippets.

@VarunSriram99
Last active July 4, 2023 14:21
Show Gist options
  • Save VarunSriram99/7a8295f2c87a5cd2ad8ac3d05f933f34 to your computer and use it in GitHub Desktop.
Save VarunSriram99/7a8295f2c87a5cd2ad8ac3d05f933f34 to your computer and use it in GitHub Desktop.
Pre-commit hook to prefix the jira issue number to commit message using bash
#!/bin/sh
# Get current branch name
branch_name="$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)"
# Replace or add the board name abbreviations here
jira_abbreviations=("JIRA_BOARD_ABBREVIATION")
# Check if current branch is a feature branch i.e. starts with a ticket number
check_is_issue_branch () {
for abbrv in "${jira_abbreviations[@]}"
do
if grep -i "^$abbrv" <<< "$branch_name"; then
return 0
fi
done
return 1
}
# Check if user already prefixed the issue number to the code
check_is_commit_prefixed () {
commit_msg="$1"
for abbrv in "${jira_abbreviations[@]}"
do
if grep -i "^$abbrv" <<< "$commit_msg"; then
return 0
fi
done
return 1
}
# Attach the prefix to commit message
attach_prefix () {
file_path="$1"
commit_msg="$(<$file_path)"
check_is_commit_prefixed "$commit_msg"
if [ "$?" = 1 ]; then
delimiter="-"
combined_branch_name=$branch_name$delimiter
split_branch_name=();
while [[ $combined_branch_name ]]; do
split_branch_name+=( "${combined_branch_name%%"$delimiter"*}" );
combined_branch_name=${combined_branch_name#*"$delimiter"};
done;
commit_prefix="${split_branch_name[0]}-${split_branch_name[1]}"
commit_msg="${commit_prefix} ${commit_msg}"
echo "$commit_msg" | tee "$file_path"
fi
}
# Path to commit message
file_path=$1
# Getting the current commit message
commit_msg="$(<$file_path)"
check_is_issue_branch
if [ "$?" = 0 ]; then
attach_prefix "$file_path"
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment