One thing that bothers me is that I always forget how to revert commits properly. So I decided to finally write a quick "cheatsheet" on how to revert commits on various cases.

Undo a whole commit by creating a new commit that undoes the changes

If you want to revert any commit with all its changes, but not lose the original commit but still keep the current branch no longer afected:

$ git revert <commit-id>

Example:

/t/project ❯❯❯ git revert a874f926b6cec5846e478ad3ea1b03a14c0ab3c6
/t/project ❯❯❯ git log
commit c5e767fc4cb6153603cf7987dd8244367463a54c (HEAD -> refs/heads/master)
Author: Ben Mezger <me@benmezger.nl>
Date:   Sat Nov 25 19:53:20 2017 -0200

    Revert "net.c: Fixed socket call"

    This reverts commit a874f926b6cec5846e478ad3ea1b03a14c0ab3c6.

commit ca343cef332eed3fcbf119f5f1df0637ea62626e
Author: Ben Mezger <me@benmezger.nl>
Date:   Sat Nov 25 19:52:07 2017 -0200

    net.c: Break if no new connections was detected

commit a874f926b6cec5846e478ad3ea1b03a14c0ab3c6
Author: Ben Mezger <me@benmezger.nl>
Date:   Sat Nov 25 19:51:34 2017 -0200

    net.c: Fixed socket call

Delete the last commit from remote

This will rewrite history. Think about it twice before doing this.

Say we want to remove the top commit from a remote origin, we can force the branch of the origin’s remote repository to the parent of that commit:

$ git push origin "+<commit-id>^:<branch>"
(don’t ignore the + (plus sign) and the ^ (caret sign))

The caret sign (^) means the parent of the commit-id and the plus sign (+) as a forced non-fastforward push.

Delete the last commit from a checked out (locally) repository

You can do the previous command easier if you are checked out locally.

$ git reset HEAD^ --hard

Then finally push your deleted commit to your remote:

$ git push origin <branch> -f

That’s all for today folks.