We’ve all been there at some point. A rebase here, an unsuccessful merge there – and your branch is pretty much broken. If only you could go back in time to the point where things were working! Well, turns out you can.
git reset --hard origin/branch-to-reset
git clean -d -f -x
If you just want to nuke all local changes and get the latest working state from a tracking remote branch, this is for you. First, fetch the latest state from the origin and checkout the branch to reset (of course, these steps are optional if you are already on the branch and have the latest changes). Then, you reset your local branch to the current head of the tracking remote. The –hard switch will make sure to not only reset the index but also the whole working tree, so that any changes made to tracked files are discarded there. The clean command in the end will recursively purge any remaining untracked, ignored and non-ignored files and directories respectively. You should now be on par with the remote again!
Another, shorter way to achieve the same result would be to do
git switch -C branch-to-reset origin/branch-to-reset
which is nice, but the documentation at the time of writing warns that this command is experimental and the behavior may change
git reset does accept commit hashes, too. So you could also go back to a particular commit instead. You can conveniently list commits and their hashes with
git log –pretty=oneline.