How to fix the oh no! I committed on master from within Visual Studio – 100

Previously, I’ve blogged about how to get uncommitted changes off of master onto a new branch and I’ve blogged about how to get committed changes off of master onto a new branch from command line. Today’s tip fixes the oh no! I’ve been committing on master this entire time from within Team Explorer, thanks to blog reader Luke Kolodziej

Let’s say you’re motoring along and you realize that you’ve been checking into master (or some other wrong branch) this entire time.

history of master branch showing oops! commits

Don’t delete your .git folder! There’s a better way!

First, create a branch but do not check it out!

Go to Team Explorer – Branches, then Right Click on master and select New Local Branch From. Now in the TE window, give your new branch a name, but uncheck the checkout branch.

Checkout branch unchecked

Click Create Branch.

Now you’ll go back to your History – Master tab and do a Reset – Delete Changes (–hard) on 2nd to last commit. We’re defaulting to –hard because we have no uncommitted changes in working directory or in staging.

Reset - Delete Changes in master on previous commit

Now hit Refresh on the History – Master tab and you’ll see that your commits are no longer on master.

I need to be on my own branch commit gone from master

But where did this commit go?

Remember the visualization from the previous tips. Just because we rolled back the HEAD pointer doesn’t mean the commit is lost. Remember git reflog holds the truth!

Okay, now if you switch to the newline branch (e.g. using the status bar button at the bottom right), and going to View History (either from Branches – Actions – View History or from Status bar – branches list – View History)

I need to be on my own branch still on newline

I still to this day feel freaked out that this works. One day I’ll be able to conceptualize master, HEAD, branches, etc as pointers versus the other way around (i.e. commits suddenly disappearing if they don’t show up in the git history). One day.

2 thoughts on “How to fix the oh no! I committed on master from within Visual Studio – 100

  1. Okay, now if you switch to the master branch (e.g. using the status bar button at the bottom right)

    Did you mean to say switch to the ‘newline’ branch?

    Like

    1. Ah thanks for catching that! I can’t type fast enough to keep up with what’s going on! And also thanks for the validation that people are reading 🙂 Your feedback makes my day!

      Like

Leave a comment