January 7, 2020

Repost: So, you forgot to make a git branch?

Repost: So, you forgot to make a git branch?

(originally posted to my blog in June 2015)

It happens to me at least once a week. I meant to make a topic branch. But I dove into the code too quickly - and suddenly I am a couple of commits into what at the moment seems like an important feature or bug fix, and I realize - I have committed to the master branch. This is a big no no in our company - bypassing code review, and a push on master most often means instant deploy.

But do you remember what to do, when you want the commits into a new branch?

Four easy steps back to safety

Just create the new branch.

git checkout -b new-branch-name

Ensure that everything is commited

Change back to your master branch

git checkout master

Now reset the master branch back to the commit id it had before.

git reset FORMER-COMMIT-SHA --hard