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:
- I’ve accidentally used git add . and added files that I didn’t mean to add to staging
- 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.
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”
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.
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.
And lastly doing a git checkout — Program.cs will undo all changes to that file to the last commit.
One thought on “How to undo changes to a file that has been staged in Visual Studio – 071”