The optimal strategy to fix depends primarily on two questions:
- Have you already committed the mistakes?
- if it's committed, have you already pushed them to the remote repository?
Before we begin, I want to clarify the concept of HEAD in git, we will be referring to this many times throughout the post.
Think of HEAD is like the head of a cassette player. Your commits are the recordings on the tape. It's just a reference to a commit. The HEAD is usually pointing the latest commit. But you can change it to any commit from history.
Fixing uncommitted mistakes
This is generally easier than fixing committed mistakes.
git reset —hard HEAD
This will throw away all the tracked and untracked changes. The command simply tells "make the state as it was in HEAD" (Head usually points the latest commit).
Let’s say the mistake was in just one file. You want to revert the edits in that file only and keep the edits in other files. You would want to choose one of the following two:
git checkout — myfile.js
Restores to the last tracked version of the file.
git checkout HEAD myfile.js
Restores HEAD state of myfile.js
Fixing committed mistakes
Caution: It’s a good idea to create a separate branch as a backup of your works before you mess with the commit history. So that you could always go back to original state easily in case of a mishap.
If you have not pushed to the remote repository:
git commit —amend
It overwrites the previous commit. Just make and add your changes. You can also change the previous commit message.
If you have pushed to the remote repository:
git commit —amend will also work if you have already pushed the mistakes to the remote repository. However, since it modifies the already existing history by replacing the last commit, the remote repository will reject the push. You will have to push the changes with the force flag (-f).
git revert HEAD
This command is quite effective yet very easy to use. Git revert automatically reverts edits in a specified commit by creating a new commit. You can specify a hash as well. e.g git revert 59c964d will revert changes in commit 59c964d and not touch anything else.