On a Windows NT system, is there a way to quickly delete directories (from within a Ruby script) that may have read-only files in them. The command I’ve been using is
File.delete(Dir[".*"])
but this crashes when it hits a RO file.
Similarly, is there a way to force the overwriting of a RO file? I’ve been using File.syscopy, but this, too, crashes when attempting to overwrite an RO file.
On a Windows NT system, is there a way to quickly delete directories (from within a Ruby script) that may have read-only files in them. The command I’ve been using is
File.delete(Dir[".*"])
but this crashes when it hits a RO file.
Similarly, is there a way to force the overwriting of a RO file? I’ve been using File.syscopy, but this, too, crashes when attempting to overwrite an RO file.
I’d suggest this: Get a list of files first and iterate over it.
Wrap in a begin/end and catch the exception. When you get the
exception for a RO file, explicitly change it to be writable
and do a retry.
Something like:
files = Dir[“.”]
files.each do |file|
begin
File.delete(file)
rescue Whatever
system(“whatever #{file}”)
retry
end
end
I don’t know the exception or how to fix it in Windoze. Any other
mistakes I made are due to the lateness of the hour.
On a Windows NT system, is there a way to quickly delete directories
(from within a Ruby script) that may have read-only files in them. The
command I’ve been using is
File.delete(Dir[".*"])
but this crashes when it hits a RO file.
Similarly, is there a way to force the overwriting of a RO file? I’ve
been using File.syscopy, but this, too, crashes when attempting to
overwrite an RO file.
Thanks!
-Kurt Euler
Try the standard library file ‘fileutils.rb’. You can RDoc the file to
see some documentation or (of course) look at the file directly.
From memory:
require ‘fileutils’
FileUtils.rm_rf(directory) # trash a directory tree
FileUtils.cp(src, dest, :force => true) # copy over a RO file
These use Unix names, but I imagine it will work on Windows.
FileUtils.rm_rf(directory) # trash a directory tree
FileUtils.cp(src, dest, :force => true) # copy over a RO file
These use Unix names, but I imagine it will work on Windows.
Looks like it will (remove_file is ultimately called by rm_rf and
variants…)
def remove_file( fname, force = false ) #:nodoc:
first_time_p = true
begin
File.unlink fname
rescue Errno::ENOENT
raise unless force
rescue
if first_time_p
# try once more for Windows
first_time_p = false
File.chmod 0777, fname
retry
end
raise
end
end
A slightly more direct version, which I know is good for Windows, but
not verified on *nix[1]:
files.each do |file|
# make writable to allow deletion
File.chmod(0644, file)
File.delete(file)
end