the case of undoing

  • the question is how to undo the things in git
  • currently, 3 RESETS AND 1 CHECKOUT

toc

findings

(1) RESET ➔ git reset HEAD: undo the stage

(2) RESET ➔ git reset –soft HEAD~1: undo the commit, keep the stage

scenario: I stage 50 small changes, commit them in bulk and push it to the jekyll pages. The build fails. I need to undo the commit and start analyzing where it went wrong.

  • you have staged many files
  • you commit them at once from the INDEX into HEAD
  • UNDO just the commit and put it all back to the index, you move the HEAD to the commit before
  • this brings files back to INDEX
  • this does not change any files themselves

(3) RESET ➔ git reset –hard HEAD~1: undo the commit; undo the stage; keep files

scenario: I hit a wrong button in VSCode sometimes and I stage or even commit everything

  • Then I need to undo that step in a terminal quickly
  • run git reset --hard HEAD^
  • If multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits.
  • You can increase the number to remove even more commits.

(4) CHECKOUT ➔ git checkout: undo local uncommitted file changes

  • DANGEROUS

scenario: working on something and you just don’t want to create .old, i.e. you just want to be able to go to the last commit of that file

  • Commit (i.e. CHECK-IN) version_1 that would like to use as a restore point
git add foo.bar && git commit -m foo-bar -RESTORE point
  • this file in that state is commited and is waiting to be pushed
  • start working and experimenting
  • discarding local changes (permanently) to a file: git checkout --<file>
git checkout -- 2020-07-17.js
  • the file will be OVERWRITTEN
  • if I want to return to a particular version of the commit I combine the SHA with the filename
git checkout 55fc911 "2020-05-18.js"

restore_deleted_file

  • NOTE:

I’ve always been uncomfortable with this GIT CHECKOUT command because it’s used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).

https://stackoverflow.com/a/215731

(5) REVERT

scenario: you made a change, commited it, and pushed to remote (like test the change of a config file on github pages). You made a mistake. You realized immediatelly. How to undo now?

  • the obvious way is to undo in a new commit/push
  • the less obvious, good for training, way you revet a commit, whic his CREATING A NEW COMMIT UNDOING ALL CHANGES MADE IN THE BAD COMMIT
  • the following is for the forceful removal of the last commit both locally and in the remote branch
git reset HEAD^ --hard
git push origin master -f

sources