Recovering a dropped Git Commit

After pushing a commit or merging a pull request, one may accidentally drop a Git commit from branch history. If the commit was part of a pull request, GitHub will not reopen a closed pull request whose source branch no longer contains the commit. Instead, check whether the commit still exists in git reflog by searching for its message or hash.

git reflog

If the commit exists in the reflog, recover it using the commit hash:

git checkout -b recovered-branch <commit-hash>

If the commit is not in the reflog, it may still exist as an unreachable object or in another branch or remote. Note the reflog is local: it only records commits that existed in the local repository.

To search for unreachable (dangling) commits:

git fsck --unreachable

For example, to check all branches for the specific commit:

git branch --contains <commit-hash>

To check all remotes for the commit:

git fetch --all
git branch -r --contains <commit-hash>

If the commit is found in another branch or remote, recover it by checking out that branch or creating a new branch from the commit hash.

If the commit is only found in someone else’s repo (perhaps the person that made the pull request), obtain the commit URL and apply it like:

curl -L https://github.invalid/user/repo/commit/hash.patch | git am

git am is used instead of git apply because it creates a commit that preserves the original author and commit message, ready to push.