Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find all empty directories in an svn checkout
require 'find'
dir_to_scan = '.'
dir_to_scan = ARGV[0] if ARGV.count == 1
dirs = []
# First collect all directories, but ignore anything with .svn in it
Find.find( dir_to_scan ) do |entry|
next if entry =~ /\.svn/
next if not File.directory?(entry)
dirs << entry
end
# Sort directory by slashes and then by string length so that the deepest
# directories will come first
dirs.sort! do |a,b|
aa = a.count('/');
bb = b.count('/');
next b.length <=> a.length if aa == bb
bb <=> aa
end
dirs_count = {}
# fetch the dirs and count number of subdirs, excluding .svn again
dirs.each do |dir|
dirs_count[dir] =
Dir.entries(dir).collect { |e|
case e
when '.svn'
nil
when '.'
nil
when '..'
nil
else
e
end
}.compact.count
end
last_dir = nil
empty_on_current_level = 0
dirs_count.each do |dir,count|
if last_dir == nil
last_dir = dir
next
end
# is the last entry on the same level as the current one and are both empty
reset_empty = false
if last_dir.gsub(/\/[^\/]+$/, '') == dir.gsub(/\/[^\/]+$/, '')
if dirs_count[last_dir] == 0 and dirs_count[dir] == 0
empty_on_current_level += 1
end
else
reset_empty = true
end
# is the directory before a direct child and is it empty?
if last_dir.length > dir.length and last_dir.index(dir) == 0 and last_dir[ (dir.length)..-1 ].index('/') and dirs_count[last_dir] == 0
# then assume we would delete that dir and decrease the count on the
# current directory
dirs_count[dir] -= (1 + empty_on_current_level)
end
empty_on_current_level = 0 if reset_empty
last_dir = dir
end
dirs_count.each do |dir,count|
puts dir if count == 0
end
@atimb
Copy link

atimb commented Jan 9, 2013

Nice work. Unfortunately in case of a more complicated directory structure this does not work properly. See my fork for the fix: https://gist.github.com/4496313

@saltsurge
Copy link

saltsurge commented Feb 1, 2013

Really helpful, thanks,

@simstern
Copy link

simstern commented Mar 27, 2013

thanks a lot, works perfect for me!

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