The Problem
If you find yourself in a situation where you need to delete your Git history, you can use the git reset --hard command to wipe out the commits you want to delete and the working files that you have.
This is useful when you want to forget a day in the life of a software developer that you'd rather not remember, such as when Mrs Peel tells you that John's done some changes that make your work redundant. However, it's important to think carefully before using this command, as it will permanently delete the commits and your working files.
The Solutions
The One Line Fix
This command deletes the last two commits, and all of your working files. For more cautious solutions, look further below.
The Git reset command will copy the last commit hash to a file called .git/ORIG_HEAD if you want to remind yourself of it another time:
Or use this, which has the identical effect:
Just Deleting Your Working Files
This command wipes out all your working files and the index, without affecting your commits:
Keeping a Backup
You can keep a backup in two ways. Firstly you can put a copy of your working files in stash:
And this command creates a new branch called my-rewind. It doesn't have the latest two commits on the main branch, but is otherwise the same.
So your main branch will continue to have those two commits, until you delete the branch later on. Much safer:
git checkout -b my-rewind HEAD~2
Recovering Deleted Commits
This can get you out of a lot of trouble. It won't replace any working files you've deleted, but this will roll back the last commands that have affected your branches.
If you need to undo the last command that affected your branches, you can use the git reset command to tell the Git reflog to go back to its penultimate state. This will undo the effect of the previous command you carried out, such as a reset on the branch. It's an irony that the undo for a hard reset is... a hard reset. In fact, this command can undo many actions that you take on a branch, including commits, checkouts, and cherry picks.
But for now, this will simply undo your branch reset action:
git reset --hard HEAD@{1}
But if you want to save the most time, try a
free for any use Git client. It might be the best move you'll ever make with Git.