Can I get git fsck to show commit names?

This is not an answer solving this with git fsck, but something which might work in this situation.

git reflog outputs a list of past HEADs in the repository. For example, if you switch from a branch master to a branch devel, this produces a reflog entry with the HEAD of the master branch.

So if the commit was part of a branch at some time, the chances are great that you can recover it using a combination of git reflog, git log and a bit of manual work.

There are a few cases:

  1. Just fire up git reflog and scroll through it. If it shows the commit message you were looking for, that’s great! Copy the commit ID and use it for whatever you want (e.g. git cherry-pick, or save it into a branch using git branch save-my-commit commitid).

  2. The commit is not directly in git reflog, but you see a commit which you made after the commit you want to find (and before deleting it). In that case, use the commit ID of the commit you made afterwards as found in git reflog and pass it as argument to git log: git log commitid. Scroll through the output and see if you can find your commit. Use the commit ID as in case 1.

  3. The commit is not directly in git reflog and you do not find a commit of which you know that you made it after the commit you deleted and before deleting it.

    This is the most tedious case, in which case it might be easier to go through the other processes here. I am not sure though that they will actually be listed as dangling commits, so it is worth a shot if you cannot find your commit using git fsck.

    Go over all entries in git reflog and use the commit IDs as argument to git log as described in case 2. Try to find the commit you are after.

Good luck!


This works on Linux and Mac:

git fsck --lost-found | grep "dangling commit" | \
   cut -d" " -f 3 | xargs -I "{}" git --no-pager show --stat "{}"

With pager and more like git log (kudos to Rafał Cieślak):

git fsck --lost-found 2>/dev/null | grep "dangling commit" | \
    cut -d" " -f 3 | \
    xargs -I "{}" git --no-pager show --no-patch --format=format:"%h <%an> %s%n" "{}" | \
    less

I'm not sure if you have grep and xargs in the Windows git shell.

Explanation:

  • git fsck finds the data
  • grep reduces that to only the dangling commits
  • cut leaves only the commit ID
  • xargs runs the command git show --stat with the IDs

[EDIT] Fixed for cases when there are several dangling commits.

Tags:

Git