Skip to content

Instantly share code, notes, and snippets.

@alexmchale
Created October 31, 2012 19:04
Show Gist options
  • Save alexmchale/3989147 to your computer and use it in GitHub Desktop.
Save alexmchale/3989147 to your computer and use it in GitHub Desktop.
This is a simple script for getting a list of dangling commits in a git repository and the description of the log entry to identify it. This is helpful in finding lost commits in a git repository.
#!/usr/bin/env ruby
# Make sure we're at the root of a git repository.
if ! File.directory? ".git"
puts "please run this from the root of a git repository"
exit 1
end
# Get a list of dangling commits from fsck.
fsck = `git fsck --lost-found 2>&1 | grep "dangling commit"`
# Clean up the list so we have just a list of SHA-1s.
commits = fsck.split(/[\r\n]+/).map(&:strip).map { |c| c[/[a-f0-9]{40}/] }
# Get the oneline description of each commit.
logs = commits.map { |c| c + `git show --oneline #{c} 2>&1 | head -n 1` }
# Remove the partial SHA-1 added by "git show" in favor of the full SHA-1 we
# prepended above.
logs.each { |log| log.sub! /[a-f0-9]{7} /, " " }
# Print the results.
logs.each { |log| puts log }
@dougpagani
Copy link

This is a great little-scriptlet -- I've thrown in an alias "grepDanglers" into my dotfiles.

Thank you for sharing!

@jbisotti
Copy link

I believe this Bash-only version would work similarly; however, it would print the partial SHA (not sure that matters for most cases)...

git fsck --lost-found | grep "dangling commit" | cut -d ' ' -f 3 | xargs git log --oneline --no-walk

@dltacube
Copy link

dltacube commented Apr 9, 2021

I believe this can be slightly shorted to:

git fsck --lost-found --dangling 2> /dev/null | cut -d ' ' -f 3 | xargs git log --oneline --no-walk

--dangling removes other things like blogs and 2> removes the first 2 lines.

@DNonov
Copy link

DNonov commented Jun 22, 2024

@dltacube 2>/dev/null won't remove the first 2 lines but will redirect the stderr to /dev/null.

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