Git Hooks is an amazing tool to automate actions before or after executing a git command. Some common scenarios where we can use hooks are:
- Validate the format (using eslint for example) before a commit
- Validate the commit message format
- Update a version of a file or settings
- Add a default text in the commit message
In this article, we will learn how to add as a default text the branch name in the commit message. Creating a new branch for each new story and naming it after the associated ticket or story number is crucial for maintaining a well-organized and structured development process. This way, you can do things like automatically move the ticket to "doing" status when the branch is created or create a link between the user story and each commit in the branch.
Some examples of user story numbers in Jira or other bug trackers are:
U-0001
COMP-0001
STORY-001
To create our hook for adding the branch name in the commit message we need to navigate to the hooks' folder in our projects.
Navigate to your folder's project and open .git folder and then hooks folder. There you will find some default templates to create your own hook.
Example on macOS:
Now you have to create a file with the name prepare-commit-msg. Prepare commit message is the action executed before setting the message in the commit.
Within prepare-commit-msg file you need to add the following code:
# prepending commit message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop release)
fi
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s/^/$BRANCH_NAME - /" $1
fi
Bash
In line number 13 (sed -i.bak -e "1s/^/$BRANCH_NAME - /" $1
), you can see how the branch name is set. You can add more default text or words after the branch name. In this case, we only have a dash.
By utilizing this configuration, all you have to do is input your message, and it will automatically include the branch name at the start of the commit message.
Top comments (0)