I make changes to a file, and then subsequently reset my branch using git reset --hard
to origin. I want to recover the contents of that file, even after a hard reset
git reflog | grep <branch name>
Look for an entry like b65de9d HEAD@{75}: reset: moving to origin/<branch name>
. This is the point at which you reset your branch to origin. You want to use the point before that revision (e.g. increment the number by one to go back in history just before). In this case, it would be HEAD@{76}
.
git log -p HEAD@{76} -- /path/to/file
Or if you don't remember the filename, or path to the file, you can omit the --- /path/to-file
arguments. This will show you a list of all changes at this revision
You have several options depending on what is most effective. You can either reset your branch to this revision, cherry-pick this commit, create a format-patch, or simply output the file using shell redirection.
I opted for output redirection since I don't have an interest in restoring the branch, and the team member needing this file may not necessarily have my local commits in his copy of the branch (I don't think I pushed my changes). I didn't want to format-patch the changes because the file was introduced with other changes, and changes to it spanned across multiple commits.
git show HEAD@{76}:/path/to/file > /path/to/output