Hi All !
I'm a tech lead, and I'm on charge to check Pull Request/Merge Request on my team. And also to create release notes (CHANGELOG.md) on each release.
So, my first problem was to resolve the commits of the developers, that they always have some mistake, or have errors into the commit message (without correct format), or errors in the branch name.
I searched and I found different solutions. A lot of them need to use an external software, like node (npm library), or php composer library, etc. And the projects are in different technologies, like Android, PHP, .NET, etc.
After checking all that I found, I created a solution that works in all environments without external dependencies.
The solution is really easy.
You need to follow these easy steps
- create .git-hooks folder into your project root directory, at the same level you already have .git folder
- create 2 files into this folder: pre-commit and prepare-commit-msg (these two files don't have an extension)
- put the correct code into each file (I will add them below these steps)
- run this command in your command line, into your main folder of your project (one level up from .git-hooks): git config core.hooksPath .git-hooks
- READY !
pre-commit file code:
#!/bin/bash BRANCH=$(git rev-parse --abbrev-ref HEAD) REGEX="^(dev|release)-([0-9]+)-q([0-9]+)\.([0-9]+)\.(.+)$" if ! [[ $BRANCH =~ $REGEX ]]; then echo "Your commit was rejected due to branching name" echo "Please rename your branch with '(dev|release)-YYYY-qX.X.X' syntax" exit 1 fi
prepare-commit-msg file code:
#!/bin/bash MESSAGE=$(cat $1) COMMITFORMAT="^(feat|fix|docs|style|refactor|test|chore|perf|other)(\((.*)\))?: #([0-9]+) (.*)$" if ! [[ "$MESSAGE" =~ $COMMITFORMAT ]]; then echo "Your commit was rejected due to the commit message. Skipping..." echo "" echo "Please use the following format:" echo "feat: #1234 feature example comment" echo "fix(ui): #4321 bugfix example comment" echo "" echo "More details on COMMITS.md" exit 1 fi
You can edit it according to your needs.
File pre-commit: check branch names.
In my case I filter to use only format like that:
Where YYYY is the year, and X.X.X is the version, in our case we use the Quarter number.
You could change that using regex and put what you want ;)
File prepare-commit-msg: check commit message.
In our case, we use the following format:
Off course, you could change it as your needs.
And finally, the command git config core.hooksPath .git-hooks change your local git hooks configuration to use the new path .