Automatically prefixing your commit messages with a ticket number is a good practice, especially if you are working with a team or using an issue tracking system. One way to achieve this is by using Git hooks. Git hooks are scripts that Git executes before or after certain events, such as committing or pushing. Here's a simple example of a Git hook that automatically adds a ticket number to your commit message. This example assumes that your ticket numbers are in the form of, for example, hotfix/ABC-123, and you want to use this format in your commit messages.
Open your terminal.
Navigate to the root directory of your Git repository.
Create a file named prepare-commit-msg in the .git/hooks/ directory. If it doesn't exist, you can create it. Make sure the file is executable.
touch .git/hooks/prepare-commit-msg
chmod +x .git/hooks/prepare-commit-msg
To open the prepare-commit-msg file using TextEdit from the terminal, you can use the open command. Here's the command you can use:
open -e .git/hooks/prepare-commit-msg
In a text editor, and add the following script:
#!/bin/bash
COMMIT_MSG_FILE=$1
# Check if the commit message contains a ticket number
if ! grep -q "^\[[A-Za-z]+/[0-9]+\]" "$COMMIT_MSG_FILE"; then
# Extract the feature name from the current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
# Add the branch name to the beginning of the commit message
sed -i.bak -e "1s|^|\[$BRANCH_NAME\] |" "$COMMIT_MSG_FILE"
fi
You can check if the prepare-commit-msg file is executable by using the ls command with the -l option, which displays detailed information about files. Navigate to the .git/hooks/ directory and run:
ls -l prepare-commit-msg
This will show you detailed information about the file, including its permissions. If the file is executable, you should see an "x" in the permission section. Here's an example:
-rwxr-xr-x 1 user group 1234 Dec 14 12:34 prepare-commit-msg
The resulting commit message should now look like this:
[feature/header_add_nav_bar] add nav bar.
Top comments (0)