Git revert
Use `git revert` to undo the changes introduced by a commit without removing that commit from history. Git normally records the undo as a new commit, so it works well on shared branches.
Also known as: git revert, откат коммита
What gets undone?
Suppose a commit on main changes the default page size from 20 to 100. The higher limit causes a performance regression, but the next commit fixes an unrelated display bug. Reverting the page-size commit can restore the old limit without dropping the display fix. The branch history still shows the original change and the commit that undid it.
How it works
For an ordinary commit, Git compares that commit with its parent to determine what it changed, then tries to apply the inverse of those changes to the current branch tip. It does not check out the old snapshot. If the revert succeeds, Git normally creates a new commit on top of the current one.
Start with a clean working tree. Use git log --oneline to find the commit ID, then run:
git revert a1b2c3d
git show HEAD
The second command shows the resulting commit and its diff. Review that diff and run the relevant tests before pushing or opening a pull request. A clean revert only means Git could apply the edits without a conflict; it doesn't guarantee that newer code still works without the reverted change.
Handling conflicts and reviewing changes first
Git may stop if later commits edited the same lines. Resolve the conflicts so the files keep the changes you still want, stage the resolutions with git add, then run git revert --continue. To cancel the operation while it's in progress, run git revert --abort.
If you want to inspect or adjust the changes before committing, use git revert --no-commit a1b2c3d. This applies the inverse changes to the working tree and staging area without creating a commit.
Reverting a merge
A merge commit has more than one parent. git revert -m 1 <merge-commit> tells Git to use the first parent as the baseline for deciding what the merge changed. That's usually the tip of the branch you merged into, but check the parent order rather than guessing. Reverting a merge changes the files, not the commit graph. Merging the same branch again does not, by itself, bring back the already merged changes that the revert removed. To reintroduce them, you may need to revert the revert or apply a corrected change in a new commit.
Interview question: revert or reset?
If a bad commit has already been pushed to a shared branch, git revert is usually the right choice: it adds a commit that teammates can pull normally. Resetting the branch to an earlier commit moves its pointer backward; publishing that move usually requires a force push. Also distinguish a Git revert from a deployment rollback: a revert changes the repository, but doesn't switch the running application to an earlier build.