Backtracking #
We already saw how a file can be unstaged (with git reset
) before it is committed.
If the file was committed by mistake, then there are at least three scenarios.
Reset #
If the commits that contain the file have not been shared yet with a remote, then these commits can be cancelled locally. The command
git reset <ID>
moves the pointer for the current branch “back in time” to the commit <ID>
.
This has the effect of deleting all posterior commits.
Revert #
If the commits that contain the file have been shared with a remote, then git revert
is often recommended by default.
This command does not affect the history of a branch (as opposed to git reset
).
Instead, if adds a commit to the history that reverts the k last commits on the current branch.
For instance
git revert HEAD
adds a commit that reverts the latest one.
And
git revert HEAD~3..
adds a commit that reverts the 3 latest ones.
Rewriting history #
In some (rare) scenarios, one may need to rewrite the history of a branch that has already been shared.
For instance, sensitive information (passwords, etc.) or a large dataset may have been committed by mistake.
Dedicated tools may be used in such scenarios.