What I did was making a pre-push bash script and commit it inside the repository. Then call this script from husky pre-push hook with husky parameter.
This is my husky configuration inside package.json (you can set separated config if you want)
"husky": {
"hooks": {
"pre-commit": "./commands/pre-commit",
"pre-push": "./commands/pre-push $HUSKY_GIT_STDIN"
}
},
as you can see I have 2 scripts, one for pre-push and one for pre-commit.
And this is my commands/pre-push
script
#!/bin/bash
echo -e "===\n>> Talenavi Pre-push Hook: Checking branch name / Mengecek nama branch..."
BRANCH=`git rev-parse --abbrev-ref HEAD`
PROTECTED_BRANCHES="^(master|develop)"
if [[ $1 != *"$BRANCH"* ]]
then
echo -e "\nπ« You must use (git push origin $BRANCH) / Anda harus menggunakan (git push origin $BRANCH).\n" && exit 1
fi
if [[ "$BRANCH" =~ $PROTECTED_BRANCHES ]]
then
echo -e "\nπ« Cannot push to remote $BRANCH branch, please create your own branch and use PR."
echo -e "π« Tidak bisa push ke remote branch $BRANCH, silahkan buat branch kamu sendiri dan gunakan pull request.\n" && exit 1
fi
echo -e ">> Finish checking branch name / Selesai mengecek nama branch.\n==="
exit 0
The script basically will do 2 things:
- This script will block anybody who tries to push to a certain branch (in my case I don't want anybody -including myself- to push directly to
master
and develop
branch). They need to work in their own branch and then create a pull request.
- This script will block anybody who tries to push to a branch that is different from their current active branch. For example you are in branch
fix/someissue
but then you mistakenly type git push origin master
.
For more detailed instructions you can follow from this article:
https://github.com/talenavi/husky-precommit-prepush-githooks