14. Cancelling commits

Goals

  • 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, and 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

Replace hello.html with the following file.

File: hello.html

<html>
  <head>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <!-- This is an unwanted but committed change -->
  </body>
</html>

Run

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.

Run

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:

Result

$ git revert HEAD
[main 86364a1] Revert "Oops, we didn't want this commit"
 Date: Tue Nov 28 05:51:38 2023 -0600
 1 file changed, 1 deletion(-)

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.

04 Check the log

Checking the log shows the unwanted cancellations and commits in our repository.

Run

git log

Result

$ git log
86364a1 2023-11-28 | Revert "Oops, we didn't want this commit" (HEAD -> main) [Alexander Shvets]
6a44bec 2023-11-28 | Oops, we didn't want this commit [Alexander Shvets]
b7614c1 2023-11-28 | Added HTML header (tag: v1) [Alexander Shvets]
46afaff 2023-11-28 | Added standard HTML page tags (tag: v1-beta) [Alexander Shvets]
78433de 2023-11-28 | Added h1 tag [Alexander Shvets]
5836970 2023-11-28 | Initial 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.

05 Next

Next let us look at the technique that can be used to remove the last commit from the history of the repository.