Is it possible to setup pre-push hook with Husky to prevent pushing to master by mistake?? Husky documentation is very poor so I couldn't find the answer.
Right now I have husky set for committing and pushing like this:
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"pre-push": "npm run lint"
}
},
"lint-staged": {
"linters": {
"*.{js,json,scss,md}": [
"prettier --write",
"git add"
],
"*.js": [
"eslint -c .eslintrc --fix",
"echo test",
"git add"
]
}
}
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:
master
and develop
branch). They need to work in their own branch and then create a pull request.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