Delete hidden files in Ruby - ruby

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 ?

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.

.svn isn't a file, it's a directory.
Check out remove_dir in FileUtils.

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.

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

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) }"

Related

Ruby FileUtils.mv: Error file not found

The following piece of code should iterate over a directory list replacing the old directory name with the new one. However, the FileUtils.mv call returns no such file or directory.
I have added the line File.exists? which returns true for all paths passed to it via this loop
Dir["projects/*/*/old"].each{|dir|
Dir.chdir dir
Dir.chdir "../"
puts File.exists?("#{Dir.pwd }/old")
FileUtils.mv "#{Dir.pwd }/old", "#{Dir.pwd }/new_path"
}
Any thoughts would be greatly appreciated.
It seems that you have a folder match as well. Because, File.exists? 'folder' returns true as well.
See if you have any folders with the name old.
# This will list all directories with a name "old"
find . -name old -type d

How can I create a file on my desktop from a Ruby script?

I'm building a webcrawler and I want it to output to a new file that is timestamped. I've completed what I thought would be the more difficult part but I cannot seem to get it to save to the desktop.
Dir.chdir "~/Desktop"
dirname = "scraper_out"
filename = "#{time}"
Dir.mkdir(dirname) unless File.exists?(dirname)
Dir.chdir(dirname)
File.new(filename, "w")
It errors out on the first line
`chdir': No such file or directory # dir_chdir - ~/Desktop
I've read the documentation on FileUtils, File and cannot seem to find where people change into nested directories from the root.
Edit: I don't think FileUtils understands the ~.
~/ is not recognized by Ruby in this context.
Try:
Dir.chdir ENV['HOME']+"/Desktop"
This might help you
Create a file in a specified directory

How to delete a non-empty directory using the Dir class?

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")
causes this error:
Directory not empty - /usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh
How to delete a directory even when it still contains files?
Is not possible with Dir (except iterating through the directories yourself or using Dir.glob and deleting everything).
You should use
require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"
When you delete a directory with the Dir.delete, it will also search the subdirectories for files.
Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")
If the directory was not empty, it will raise Directory not empty error. For that ruby have FiltUtils.rm_r method which will delete the directory no matter what!
require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"
I use bash directly with the system(*args) command like this:
folder = "~/Downloads/remove/this/non/empty/folder"
system("rm -r #{folder}")
It is not really ruby specific but since bash is simpler in this case I use this frequently to cleanup temporary folders and files. The rm command just removes anything you give it and the -r flag tells it to remove files recursively in case the folder is not empty.

RubyZip - files from different directories have path in zip

I'm trying to use RubyZip to package up some files. At the moment I have a method which happily zips on particular directory and sub-directories.
def zip_directory(zipfile)
Dir["#{#directory_to_zip}/**/**"].reject{|f| reject_file(f)}.each do |file_path|
file_name = file_path.sub(#directory_to_zip+'/','');
zipfile.add(file_name, file_path)
end
end
However, I want to include a file from a completely different folder. I have a the following method to solve this:
def zip_additional(zipfile)
additional_files.reject{|f| reject_file(f)}.each do |file_path|
file_name = file_path.split('\\').last
zipfile.add(file_name, file_path)
end
end
While the file is added, it also copies the directory structure instead of placing the file at the root of the folder. This is really annoying and makes it more difficult to work with.
How can I get around this?
Thanks
Ben
there is setting to include (or exclude) the full path for zip libraries, check that setting
Turns out it was because the filename had the pull path in. My split didn't work as the path used a / instead of a . With the path removed from the filename it just worked.

What a safe and easy way to delete a dir in Ruby?

I'd like to delete a directory that may or may not contain files or other directories. Looking in the Ruby docs I found Dir.rmdir but it won't delete non-empty dir. Is there a convenience method that let's me do this? Or do I need to write a recursive method to examine everything below the directory?
require 'fileutils'
FileUtils.rm_rf(dir)
A pure Ruby way:
require 'fileutils'
FileUtils.rm_rf("/directory/to/go")
If you need thread safety: (warning, changes working directory)
FileUtils.rm_rf("directory/to/go", :secure=>true)
If some looking for answer on #ferventcoder comment -
Just a note, I found that with Windows and Ruby 1.9.3 (at least) FileUtils.rm_rf will follow links (symlinks in this case) and delete those files and folders as well. This was found based on creating a symlink with CreateSymbolicLinkW and then running FileUtils.rm_rf against a parent directory the symlinks are in. Not exactly expected behavior.
– ferventcoder
Safest way is to iterate path and delete it manually.
def rec_del(path):
if path is file call FileUtils.rm_rf - it is safe to delete even in windows
if dir call Dir.rmdir which will succeed for empty dir and dir symlink. else will get ENOTEMPTY for regular non empty dir.
iterate the dir and call rec_del for each item.
now call again Dir.rmdir which will succeed
The laziest way is:
def delete_all(path)
`rm -rf "#{path}"`
end

Resources