Git commiting on wrong branch, how to fix

Posted: 2013-09-09 in Git

So I just programmed and realized my last X amount of commits have gone into master (see picture below). I’d forgotten to create a branch. Whats worse I’d even pushed. so how to fix.

CheckingsWrongBranch

There are several ways to approach a fix.

In my case I will create a new branch (where the commits should have been), then move the commits to this branch and then rewind master and then update origin (phew).
Don’t despare its actually reallllllly simple (god i love git)

So lets begin….

Step 1 & 2 – New Branch and move commits to this branch

git checkout -b hopethisworks master

Result:

We now have our new (correct) branch and it references all the commits master branch does.

NewBranch

Step 3 – Rewind master

Time to move master back to where it belongs.
To do this find the commit you want to go back to (in my case back to the merge of branch 45) get its hash and then hard reset the branch.

To get the commit hash use either git extensions or git bash (both methods described below)

Git Extensions:
Right click on the commit and copy hash tag (see pic).

CopyCommitHash

Or

Git Bash:

Use git log (press q to exit when you have found your desired commit)

git checkout master
git log

GitLog
Now use this to do a hard reset on your master branch, make sure you move back to your master branch.

git checkout master
git reset --hard b21222917c8b1c70ad64dc2b6afdf972cb210e00

Result:
Our master is now pointing back at its rightful location
HardResetHead

Step 4 – Server cleanup

One chore left, clean up master on origin.
This is the first time in these step that you can effect others, the rest of these steps are local to your computer only and extremely easier to revert.

Simply push master to origin, this will need to be a force push (in the picture you can see the rejection notice if you don’t use the -f in the push).

git push -f

Result:
We’re done, you can now continue to work on your new branch (don’t forget to switch to it!!).

CorrectedMaster

Consider what was reversed and you start to see how great git is.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s