When handling already pushed and public commits, several methods exist for reverting them, but the safest and most common approach is to use the git revert command. This command preserves the integrity of the project history by adding a new commit that effectively reverses the changes of the previous commit.
Steps
-
Identify the commit hash to revert First, identify the hash of the commit to revert by examining the commit history with
git log.bashgit log -
Use
git revertAfter identifying the commit hash to revert, use the following command:bashgit revert <commit-hash>Here,
<commit-hash>is the hash of the commit you want to revert. -
Resolve potential conflicts If conflicts arise during the revert process, Git will prompt you to resolve them. Manually edit the files to resolve these conflicts and use the
git addcommand to mark the resolved files. -
Complete the revert operation After resolving conflicts, complete the revert operation. Typically, Git automatically opens a new commit message editor for this revert. Save and close the editor to finalize the revert commit.
-
Push changes to the remote repository Push the changes to the remote repository using:
bashgit push
Practical Example
Suppose we mistakenly committed a feature to the project and later discovered it introduced serious issues, requiring a quick revert. The commit hash is abc1234.
Steps:
bashgit revert abc1234 # Resolve any potential conflicts git push
This way, the original erroneous commit remains in the history, but we effectively undo its impact by adding a new "revert" commit.
Important Notes
- Use
git revertinstead ofgit reset, asresetalters the public history and may confuse other collaborators. - Ensure all changes are tested locally before pushing to avoid introducing new issues.
The advantage of this method is that it preserves the integrity of the project history, enabling the team to more easily track what occurred, why the revert was needed, and how the revert operation was executed.