Reputation: 1601
Can I force a git commit message to start with some text
something like:
feature: add something to UI
or
bug: fix login page error
The commit message must start with "feature:" in the above case or with "bug:" as the second example shows
if the message does not start with "feature:" or "bug:" I would like to reject the commit
Thanks
Upvotes: 1
Views: 838
Reputation: 715
Here is how you can do it
Go to your home directory and create a folder named hooks. And create hook files.
mkdir ~/hooks
cd ~/hooks
touch pre-commit
chmod +x pre-commit
touch commit-msg
chmod +x commit-msg
Our first argument $1 gives us the commit-msg file. We can read the commit message with the following command:
cat "$1"
Create this script file (Here REGEX_ISSUE_ID contains the REGEX that you want to set for your commit message format)
#!/bin/bash
REGEX_ISSUE_ID="^(ISSUE-[0-9]+|Merge|hotfix)"
ISSUE_ID_IN_COMMIT=$(echo $(cat "$1") | grep -o -E "$REGEX_ISSUE_ID")
if [[ -z "$ISSUE_ID_IN_COMMIT" ]]; then
BRANCH_NAME=$(git symbolic-ref --short HEAD)
ISSUE_ID=$(echo "$BRANCH_NAME" | grep -o -E "$REGEX_ISSUE_ID")
if [[ -z "$ISSUE_ID" ]]; then
echo "[commit-msg-hook] Your commit message is illegal. Please rename your branch with using following regex: $REGEX_ISSUE_ID"
exit 1
fi
echo "$ISSUE_ID | $(cat "$1")" > "$1"
fi
Go to the project folder and run the following command to use your hooks. You need to make this for every project that you want to use hooks.
cd <your-team-repository>
git config core.hooksPath ~/hooks
You can find more information here: https://ahmetcan.org/git-hooks-enforce-commit-message-and-branch-name/
Upvotes: 1