Created
August 14, 2019 16:58
-
-
Save bellmyer/0ff827eabfbf615256c8e8c2c2bcf129 to your computer and use it in GitHub Desktop.
Recover files that were git added, but never committed before a git-reset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
hours_ago = ARGV.shift | |
recovery_dir = ARGV.shift | |
Dir.mkdir(recovery_dir) unless File.exists?(recovery_dir) | |
# find all objects that were created less than X hours ago | |
files = `find .git/objects -type f -atime -#{hours_ago}h`.split("\n") | |
files.each do |filename| | |
# this is how git will refer to the object | |
object_hash = filename.split('/')[-2,2].join('') | |
# skip meta-objects | |
next unless object_hash =~ /^[0-9a-f]+$/ | |
# skip non-blob objects; commit messages, etc | |
next unless `git cat-file -t #{object_hash}` =~ /blob/ | |
# save blob; sorry, the names of the files themselves are not recoverable | |
`git cat-file -p #{object_hash} > #{recovery_dir}/#{object_hash}` | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After this begins the fun of grepping through possibly hundreds of files looking for your lost, scared snippet of uncommitted code. I'm rooting for you!