Emergency Git

Suppose you just goofed and think you lost some changes. Here’s a step-by-step guide in order to maximize their chance of being recovered. If you’re not already there, go to your Git repository’s directory in your favorite shell, and we’ll commence:

  1. git status to see what Git says. If you’re unfamilar with Git, do this after each step.

  2. git diff to see if your changes aren’t actually lost at all.

    • If you found them, commit or stash and be happy.

    • Maybe you already staged them? Check with git diff --staged.

  3. git fsck --lost-found to save dangling commits and objects into .git/lost-found/commit (and /other).

    • This may happen if you git add changes (and so create a blob) and then git reset --hard, discarding the staged changes.

    • Inspect the commits in .../commit with Git show, and if you find what you’re looking for, merge or cherry-pick it.

    • Search the files in .../other with grep (or better, rg) for your lost changes. They’re objects Git has in its database but can’t find from any reference. If this is where you find your lost work, you’ll need to manually graft them into your working copy (say, by replacing the corresponding file and then staging interactively).

  4. git reflog to review the chronological history of your actions with Git.

    • This displays the logged changes of the reference HEAD (what git status reports as the current branch), which is roughly equivalent to changes in the repository’s state.

    • You can browse all the changes as patches with git reflog --all -p, and then search through the output.

    • You should study the reflog and get a sense of your recent actions to help determine when your changes were lost.

    • If you find you just need to go “back in time,” you can reset your branch.

    • Writing this post made me realize “reflog” is a portmanteau of “reference log.” I’ve been pronouncing it wrong.

  5. git stash list to see if you stashed the changes.

    • git show stash@{0} --patch to see each stash.

    • I had to escape it as stash@\{0\} in Zsh.

  6. git branch --all to look for a suspicious new branch.

    • We all forget what we do sometimes, maybe you saved it to a topic branch?

    • If you’re not completely sure how Git branches work, you should study them.

  7. git log -G<regex> --patch to search the history of changes.

    • The changes could easily have been added to a recent commit without being noticed. Do some code sleuthing.

    • If you wish, rewrite your history and clean it up.

    • You should really clean up before you push.

  8. Go on your own adventure.

I hope this helped. Git does an excellent job not losing changes, but it can’t stop every mistake. Good luck with your search.