Writing a proper git message is a good coding practice. A good commit message should clearly convey what has been changed and why it has been changed. Sometimes developers use an improper message in a hurry to commit and push the changes.
To avoid such situations, we can use git hooks.
Git hooks are shell scripts placed in .git/hooks
directory of a repository. These shell scripts are executed in response to specific git events like commit messages, pushing to the repository, etc.
Here is a working hook that enforces the developer to use a commit message of 30 characters.
Please create a new file with the name commit-msg
in .git/hooks
directory of your repository. Copy and paste the below content into it.
Make this script executable using the command chmod 777 commit-msg
.
#!/usr/bin/env bash # Hook to make sure that no commit message line is less than 30 characters while read line; do # Skip comments if [ "${line:0:1}" == "#" ]; then continue fi if [ ${#line} -le 30 ]; then echo "Commit messages must be atleast 30 characters." echo "The following commit message has ${#line} characters." echo "${line}" exit 1 fi done < "${1}"
You can create and customize hooks. For example, you may start including the branch name in the commit message. This is a good practice in my opinion.
#
# Automatically adds branch name to every commit message.
#
NAME=$(git branch | grep '*' | sed 's/* //')
echo "[$NAME]" $(cat "$1") > "$1"
#!/usr/bin/env bash # Hook to make sure that no commit message line is less than 30 characters while read line; do # Skip comments if [ "${line:0:1}" == "#" ]; then continue fi if [ ${#line} -le 30 ]; then echo "Commit messages must be atleast 30 characters." echo "The following commit message has ${#line} characters." echo "${line}" exit 1 fi done < "${1}" # # Automatically adds branch name to every commit message. # NAME=$(git branch | grep '*' | sed 's/* //') echo "[$NAME]" $(cat "$1") > "$1" exit 0
Comment if you are using any other git hook to boost your productivity.