I know on various git hosting sites you can make a policy that you can't push directly to a certain branch and instead need to make a pull request - is there any way on my local repo to make sure I can't commit to those branches as well? I keep finding myself forgetting to make a feature branch, committing changes to the main branch (development, master, whatever), and having to cherry pick them out and reset or reclone in order to get my local branch in sync with the server.
1 Answers
I do that all the time. You don't have to go through all that trouble to fix it. Say I am on branch develop
and commit to it by mistake. All I have to is create the feature branch I should have created before:
git checkout -b myfeature
Then, since I haven't pushed develop
, I can simply delete my local develop
branch:
git branch -d develop
That's it! It's all sorted, as if I had created the branch before I did the commit.
Your new myfeature
branch already has the commit you made and origin/develop
does not, since you never pushed develop
. It's exactly as you want it.
The next time you do
git checkout develop
you will be at the commit before your myfeature
branch, since git
will place develop
at origin/develop
.
There is no need to prevent yourself from committing to your local develop
. This "mistake" is so easy to fix, I don't even consider a mistake. It doesn't really matter either way to me whether I create my feature branch before or after I commit.
<soapbox>Take some time to learn how git
really works. There are tons of tutorials. Don't just stop with the bare minimum of knowledge. It will save you tons of time over the long run.</soapbox>

- 37,465
- 35
- 132
- 205