tags:

views:

474

answers:

5

Does anyone know how to delete all files in a directory with Ruby. My script works well when there are no hidden files but when there are (i.e .svn files) I cannot delete them and Ruby raises the Errno::ENOTEMPTY error. How do I do that ??

Thanks in advance.

+2  A: 

.svn isn't a file, it's a directory.

Check out remove_dir in FileUtils.

Jonas Elfström
+1  A: 

It probably has nothing to do with the fact, that .svn is hidden. The error suggest, that you are trying to delete a non empty directory. You need to delete all files within the directory before you can delete the directory.

Tomas Markauskas
I think the problem is that the file *is* hidden, so it's not coming up when he lists the files in the directory using whatever method he's using so he doesn't delete them.
Matthew Scharley
He says it raises Errno::ENOTEMPTY so he probably just needs rm_rf from FileUtils.
Tomas Markauskas
A: 

Yes, you can delete (hiden) directory using FileUtils.remove_dir path.

I happend to just write a script to delete all the .svn file in the directory recursively. Hope it helps.

#!/usr/bin/ruby
require 'fileutils'
def svnC dir

    d = Dir.new(dir)
    d.each do |f|
            next if f.eql?(".") or f.eql?("..")
            #if f is directory , call svnC on it
            path = dir + "/" + "#{f}"
            if File.stat(path).directory?
                    if  f.eql?(".svn")
                            FileUtils.remove_dir path
                    else
                            svnC path
                    end
            end
      end

 end

 svnC FileUtils.pwd
pierr
Thanks pierr for the support
nash
I seem to remember you can achieve the same thing with Subversion by doing an svn export to the same folder you have the checkout.
Nigel Thorne
+1  A: 

If you specifically want to get rid of your svn files, here's a script that will do it without harming the rest of your files:

require 'fileutils'
directories = Dir.glob(File.join('**','.svn'))
directories.each do |dir|
    FileUtils.rm_rf dir
end

Just run the script in your base svn directory and that's all there is to it (if you're on windows with the asp.net hack, just change .svn to _svn).

Regardless, look up Dir.glob; it should help you in your quest.

Evan Larkin
There is a typo at the script, a dot after svn at line 2. It should be:directories = Dir.glob(File.join('**','.svn'))I tested it on both linux and windows and it works fine.
Edu
Thanks; it is fixed now.
Evan Larkin
A: 

As @evan said you can do

require 'fileutils'
Dir.glob('**/.svn').each {|dir| FileUtils.rm_rf(dir) }

or you can make it a one liner and just execute it from the command line

ruby -e "require 'fileutils'; Dir.glob('**/.svn').each {|dir| FileUtils.rm_rf(dir) }"
Jamie Cook