Dylan Smith

Recovering commits after git reset goes wrong

Today I committed to the wrong branch. All day. I started work on a new ticket but blanked on creating a branch for it, instead putting everything on the branch I used for the last ticket (which was already merged, to boot).

The good news is I knew there’s a command that would undo those commits, making it as if the files had been changed but not committed, and leaving them available to bring over to another branch. I’ve only had to use this a couple of times before so I headed over to ohshitgit.com to refresh my memory.

The bad news is that I copied the first command that looked like the one I remembered: git reset HEAD~ --hard. I knew I had five commits on the branch, so I smashed it in five times. (I’m pretty sure there’s a way to do it once and tell it you want the last five commits but whatever.) Wrong answer. They were erased from the branch, but then I couldn’t see the changes anywhere. I had a little panic thinking I lost a whole day’s work.

Reflog to the rescue

I can count the number of times I’ve had to use git reflog on, like, one finger. I remember feeling like it was magic then, and it felt the same way this afternoon.

To properly recover changes after a hard git reset when I meant to soft reset, my solution was:

git reflog show
git reset HEAD@{1}

1 should be the number, not hash, of the commit at which point you want to return to. (For me it was 8; I guess my five actual commits plus some git fuckups.) From there, I could create my new branch, bring my changed files over, and commit them again like nothing happened.

Newer Never forget where you came from Older TIL: Commit messages, SCSS in custom properties, and propagating Monstera