Skip to content

Instantly share code, notes, and snippets.

@rahul286
Forked from mfn/find-empty-dir-in-svn.rb
Created August 5, 2012 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahul286/3265556 to your computer and use it in GitHub Desktop.
Save rahul286/3265556 to your computer and use it in GitHub Desktop.
Find all empty directories in an svn checkout. Output has escaped spaces in file paths.
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.gsub(' ', '\\ ') if count == 0
end
@rahul286
Copy link
Author

rahul286 commented Aug 5, 2012

On Line #76, added support for escaping spaces in directory names. Its needed to redirect output directly to commands like xargs svn rm

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