How To Reset A Branch And Undo All Changes in Git

How To Reset A Branch And Undo All Changes in Git

Get deleted files back, undo folder structure changes and revert ALL edits with Git's Hard Reset

The Problem

This is a quick one because I have recently been playing around with the structure of my repository and created files and folders I finally decided I did not want to keep. Plus, I deleted a bunch of files I actually want back.

Ever been in the same boat?

All you want to do is just to reset back all the changes to a previous commit or branch state.

You'd expect that just by doing git checkout . everything would go back to normal... except that it doesn't. So maybe you need to git pull? Nope, that won't work either.

So what can you do to revert back ALL the edits, get deleted files back and undo folder structure changes?

The Solution

You can hard reset the local project to what's at remote or a previous commit with:

git reset --hard <COMMIT/BRANCHNAME>

For example:

git reset --hard origin/main

Warning!

Bear in mind careful while doing hard reset. It will reset everything including your configurations.

If you have any build files and config files, you might have to re-build them or check for consistency, or you might face unexpected errors due to caching issues.

Unlike the git [cherry-pick](https://git-scm.com/docs/git-cherry-pick) and the git [revert](https://git-scm.com/docs/git-revert) commands, the git [reset](https://git-scm.com/docs/git-reset) --hard command does not create a new commit. It actually rolls the HEAD reference right back to the ID of the local commit we used in the command. This isn't a matter of updating the working tree and checking out a certain version of the content of tracked files. The git reset hard command actually points the HEAD right back to the old commit and any changes to tracked files in the working tree since then are discarded.

There are other options to explore with the git reset command, including --soft and --merge. But when you've messed up and just want to undo everything, the git reset --hard command is the right one to get familiar with.

Make it a best friends if you are a developer, as you can use it as an easy way to roll back your project, which is one of the primary reasons why you probably use version control in the first place.