Un-mess Up with Git reflog!

Un-mess Up with Git reflog!
Photo by Delorean Rental / Unsplash

Have you ever done this thinking "nah, I'm good, I know what I'm doing":

git push --force

Oh.

No.

My remote branch is toast.

Yep, I've done that before. Usually it happens when I mess up a rebase and accidentally squash away a whole lotta good work.

Well, did you know you can un-mess up using git reflog.

The reflog, or reference logs, are logs of events that changed the branches you're working with or the local representation of the code you have.

Here's an example of me messing up!

touch example.txt
git commit --all --message 'add example.txt'
echo "This is an example." > example.txt
git commit --all --message 'added to example.txt'
git push
# The repo is in a good state here,
# and to make the reflog really clear,
# I've added an empty commit.
git commit --allow-empty -m 'everything is good but i am about to mess up'
git reset --hard 8caefba4eb67a2f2690d2b6704b9763c3efbc639
git push --force
# Oh.
#
# No.
#
# My remote branch is toast!

Okay, so what happened here?

  1. I added a file called example.txt and committed it.
  2. I edited the file and then committed that change too. All good so far.
  3. Then, to make this example really clear, I added an empty commit.
  4. Oh, then I reset to the previous commit because I thought I needed to.
  5. Finally I did the dangerous thing and did git push --force which will overwrite anything on the remote with what we have locally.
  6. Then I realized I messed up and went to cry in a corner.

After comforting myself with a tea, I called up my friend the reflog:

git reflog
8caefba (HEAD -> main) HEAD@{0}: reset: moving to 8caefba4eb67a2f2690d2b6704b9763c3efbc639
cc07e1f HEAD@{1}: commit: everything is good but i am about to mess up
123400a HEAD@{2}: commit: added to example.txt
8caefba (HEAD -> main) HEAD@{3}: commit (initial): add example.txt

Would ya look at that! Almost everything I did is in the reflog. It doesn't show where I did git push --force but I can see the accidental reset as the most recent reference.

To get my code back to a good state I can git reset --hard cc07e1f (the SHA where everything is good but I was about to mess up).

Okay, now that my local code is back in good shape, what do I do. Well, I have to git push --force one more time. This way git will overwrite the messed up code on the remote server with the correct code I have.

Fewf! Thank goodness for the git reference log!

Want more tricks for un-messing up git? If you haven't seen it already, check out https://dangitgit.com/en.