Forcing Semantic Release Compatible Commits
We use the great semantic-release system for our Node projects at work, which is great for automating the version numbers and change logs.
The way it works is that you format your commit messages in a particular way to mark the changes as a 'fix', 'feature' or 'breaking change' ... when semantic-release is run, it will determine what version numbers need increasing and will also generate a change log.
However, its easy to format the message incorrectly or forget completely, which will cause all sorts of issues when you try and do a release.
So I created a simple git hook to check my message format:
#!/bin/sh # Config options min_length=4 max_length=50 types=("feat" "fix" "perf") # End config options regexpstart="^(" regexp="${regexpstart}" for type in "${types[@]}" do if [ "$regexp" != "$regexpstart" ]; then regexp="${regexp}|" fi regexp="${regexp}$type" done regexp="${regexp})(\(.+\))?: " regexp="${regexp}.{$min_length,$max_length}$" function print_error() { echo -e "\n\e[1m\e[31m[INVALID COMMIT MESSAGE]" echo -e "------------------------\033[0m\e[0m" echo -e "\e[1mValid types:\e[0m \e[34m${types[@]}\033[0m" echo -e "\e[1mMax length (first line):\e[0m \e[34m$max_length\033[0m" echo -e "\e[1mMin length (first line):\e[0m \e[34m$min_length\033[0m\n" } # get the first line of the commit message INPUT_FILE=$1 START_LINE=`head -n1 $INPUT_FILE` if [[ ! $START_LINE =~ $regexp ]]; then # commit message is invalid according to semantic-release conventions print_error exit 1 fi
You can save the above script into your .git/hooks/ folder for any repos which exist already; or you can run the following commands that will set things up for every new repo you init in the future:
git config --global init.templatedir '~/.git-templates' mkdir -p ~/.git-templates/hooks cp commit-msg ~/.git-templates/hooks













