Skip to content

Instantly share code, notes, and snippets.

@bellmyer
Created August 14, 2019 16:58
Show Gist options
  • Save bellmyer/0ff827eabfbf615256c8e8c2c2bcf129 to your computer and use it in GitHub Desktop.
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
#!/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
@bellmyer
Copy link
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment