In this lesson, you will learn how to safely undo shared commits by creating a new "inverse" commit that preserves your project's history for everyone on your team.
The Problem with "Rewriting" History
When you work solo, you might use commands like git reset to delete past commits. However, once you have "pushed" your code to a shared repository (like GitHub), your teammates rely on that history. If you delete a commit that they have already downloaded, you create a "history mismatch," which causes significant headaches and merge conflicts for everyone else.
The Solution: The git revert Command
Instead of deleting a public commit, you should create a brand new commit that performs the exact opposite actions of the one you want to undo. This is known as an "inverse" or "reverting" commit. It is a non-destructive way to fix a mistake because you are technically adding new history rather than erasing old history.
To revert a specific commit, you first identify its unique identifier (the hash) using git log, then run:
git revert <commit-hash>
When you run this, Git will open your text editor to ask for a new commit message explaining why you are reverting those changes. Once you save and close, Git creates a new commit that cancels out the changes from the original.
Why This Matters for Collaboration
By using git revert, you provide a clear, traceable record of what happened in your project. Everyone on your team can see:
- The original commit where the change was introduced.
- The subsequent revert commit where the change was removed.
Because you haven’t deleted any past data, your teammates can pull these changes down without any conflict. They simply receive the new revert commit as if it were any other update. It keeps the shared history intact and keeps your team in sync.
Key Takeaway: Never delete public, shared history; instead, use git revert to create a new, inverse commit that safely cancels out the unwanted changes.