GitHub 101: Undo! A git-commit Without Losing Your Files

GitHub 101: Undo! A git-commit Without Losing Your Files

Okay so if you're wondering if that's even possible so yes that totally is possible!

Now, without any clutters let jump right into it.

Even though there are many ways of achieving desired outcome, we shall see two method of doing such.

  • Commits Not Pushed Publicly
  • Commits Pushed Publicly

Commits not Pushed Publicly

In this case we use the reset keyword to reset the git node to a previous state (HEAD) and the flag --soft is passed to see if there may be any conflicts occurring while doing so.

git reset HEAD~1 --soft

The part where ~1 is written, implies that we need to shift only 1 commit backwards. This can be any number (N) of commits As long as you know what you're doing you can read about it in more detail on the website Here

NEXT!!

Commits Pushed Publicly

Now lets say you have published the commit publicly and you want to undo that because you messed up. so,

In case you did push publicly (on a branch called 'master'):

  • Save your commit in a separate branch just in case! (so you don't have to dig it from reflog in case you screw up.

`git checkout -b MyNewBranchWithMyCommit

What this will allow us is, to move all your current changes onto a new branch name MyNewBranchWithMyCommit

Now we can proceed safely.

  • Revert commit normally as you would and push!

git checkout master git revert a8172f36

a8172f36 is the hash of the commit you want to destroy but this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history)

git push origin master

Now that, if you want to have those changes as your local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with --no-commit option:

git revert --no-commit 86b48ba

This will revert the Undo.

HAPPY HACKING! 💻🔬🧪

Leave a comment if you like it! and Let's Connect!