16. Cancelling commits
- To learn how to undo commits to the local repository.
01 Cancelling commits
Sometimes you realize that the new commits are wrong, and you want to cancel them. There are several ways to handle the issue, we use the safest here.
To cancel the commit we will create a new commit, cancelling the unwanted changes.
02 Edit the file and make a commit
hello.html with the following file.
<html> <head> </head> <body> <h1>Hello, World!</h1> <!-- This is an unwanted but committed change --> </body> </html>
git add hello.html git commit -m "Oops, we didn't want this commit"
03 Make a commit with new changes that discard previous changes
To cancel the commit, we need to create a commit that deletes the changes saved by unwanted commit.
git revert HEAD
Go to the editor, where you can edit the default commit message or leave it as is. Save and close the file.
You will see …
$ git revert HEAD --no-edit [master 45fa96b] Revert "Oops, we didn't want this commit" 1 files changed, 1 insertions(+), 1 deletions(-)
Since we have cancelled the last commit, we can use
HEAD as the argument for cancelling. We may cancel any random commit in history, pointing out its hash value.
--no-edit command can be ignored. It was necessary to generate the output data without opening the editor.
04 Check the log
Checking the log shows the unwanted cancellations and commits in our repository.
$ git hist * 45fa96b 2011-03-09 | Revert "Oops, we didn't want this commit" (HEAD, master) [Alexander Shvets] * 846b90c 2011-03-09 | Oops, we didn't want this commit [Alexander Shvets] * fa3c141 2011-03-09 | Added HTML header (v1) [Alexander Shvets] * 8c32287 2011-03-09 | Added standard HTML page tags (v1-beta) [Alexander Shvets] * 43628f7 2011-03-09 | Added h1 tag [Alexander Shvets] * 911e8c9 2011-03-09 | First Commit [Alexander Shvets]
This technique can be applied to any commit (however there may be conflicts). It is safe to use even in public branches of remote repositories.
Next let us look at athe technique that can be used to remove the last commit from the history of the repository.