How to undo changes to a file that has been staged in Visual Studio – 071

Almost always, every answer on SO for “how to undo changes to a file in Git…” starts with “well, it depends on what you mean by undo changes.” I’m starting to see why all these answers start by clarifying what you are trying to do.

Personally, there seems to be two cases where I want to “revert or undo” from staging:

  1. I’ve accidentally used git add . and added files that I didn’t mean to add to staging
  2. I’ve changed my mind on whatever code I was writing (e.g. the code didn’t do what I wanted, or more likely, never compiled) and want to pretend I never wrote it in the first place because I forgot to create a branch first

How to unstage changes in Team Explorer

Right-click on the file you want to remove from staging and select the Unstage command.

Unstage command in TE

And Team Explorer will put it back to the Changes list. You can confirm this in the command line as the file will be listed under Changes not staged for commit.

If you’re going for the destructive “let’s never speak of this code again” option, follow yesterday’s tip by right-clicking on the file and selecting the Undo Changes… command.

How to unstage changes in Command Line

Rinse and repeating for the command line, let’s stage our commit using git add Program.cs and confirm it using git status. Although git never says “staged”, you’ll just have to translate “Changes to be committed” to “These changes are staged to be committed”

git status showing a staged Program.cs

Now to unstage the changes, you can read the instructions in the git status (see above).

Running git reset HEAD Program.cs puts it back as an modified file that hasn’t been staged yet.

git reset HEAD program.cs provides feedback

Wow! Git actually provides feedback with this command. You see in the message above unstaged changes after reset. I’ll never understand why Git decides to give feedback on some commands and not others.

And doing one more git status will show you the commands to fully remove the changes, although destructive.

git status showing how to revert or undo changes to file in working directory

And lastly doing a git checkout — Program.cs will undo all changes to that file to the last commit.

command prompt showing nothing to commit

One thought on “How to undo changes to a file that has been staged in Visual Studio – 071

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