The current branch will be restored to a specified prior commit using the git reset command. By default, this command will preserve the files in the working tree while deleting commits from the history of the current branch. By doing this, you can undo one or more commits without erasing any of your work.
You must indicate the commit you want to reset to when you call git reset. You can use the tilde (~) suffix to identify an ancestor of HEAD, the current commit, or you can use the git log to obtain the hash of the desired commit. The most recent commit can be undone and redone using the commands below:
git add .
git commit -m "This commit is a mistake"
git reset HEAD~
git add main.py # need to re-add files after reset
git commit -m "This commit corrects the mistake"
To undo the last two commits, use the commands:
git add .
git commit -m "This commit is a mistake"
# make changes
git add .
git commit -m "This commit is another mistake"
git reset HEAD~2
git add .
git commit -m "this commit corrects both mistakes"
If you don’t want to have to re-stage your files after a reset, you can use the --soft flag:
git add .
git commit -m "This commit is a mistake"
git reset --soft HEAD~
# no need to git add, as files are already staged
git commit -m "This commit corrects the mistake"
The --hard flag can be used to restore the working tree and Git history to the state of a prior commit. Keep in mind that doing this would undo all tracked file modifications, even those that haven’t been committed yet.
git add .
git commit -m ""
git reset --hard HEAD~
Use of git reset --hard should be done carefully. Nevertheless, up to 90 days after they were erased, you can still use git reflog to recover any deleted changes. Git reflog will display a list of prior commits on the tips of branches when it is executed. You can select the partial hash of the commit (such as 5c8f5a7) from this list in order to restore it and make a new branch for it:
git checkout -b restored-commit-branch 5c8f5a7
Git revert can be used to produce new commits that do the opposite of current commits, i.e., removing lines and files that were added and adding lines and files that were removed, if you want to keep your repository’s history intact but restore the contents to a former state:
git add .
git commit -m "This commit is a mistake"
git revert HEAD # will create a new commit doing the opposite of the one above

