There are two ways you can use:
Option 1: protect master branch in github
Even you committed on master
branch by mistake, git will stop you to push your local master branch to github.
The way to protect master
as: in your github repo -> settiings -> branches -> choose master
-> Require pull request reviews before merging -> save changes.
So you can’t make changes on master branch directly, you should use PR to merge changes to master branch.
If you still need to make changes on master
branch directly in some way, you can use option2.
Option 2: use pre-commit hook in your local repo
In your local repo, in .git/hooks
, rename pre-commit.sample as pre-commit
. And add below script in pre-commit
:
#!/bin/sh
branch=$(git rev-parse --abbrev-ref HEAD)
if [[ $branch == "master" ]]
then
{
git reset HEAD .
git checkout -- .
echo "you tried to commit on master branch, recover master branch and stoppped! "
exit 1
}
fi
Now if you wrongly commit on master
branch, git will reset the master
branch as origin and hint you with messages.
Note: the commands git reset HEAD .
and git checkout -- .
will discard all the uncommitted changes on master
branch. It's based on the changes is useless. If you want to keep the uncommitted on master
branch, you can ignore the two commands.