[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Newbie: Recursive deletion of files and dir

FredrikC

1/22/2006 9:34:00 PM

Hi!
I'm designing (newbie level) a script to clean up empty directories and
old files recursivly. Something is wrong..works fine when not actually
deleting anything, but when I start removing files and directories it
ends prematurly.. any heklp available..?

def thisDir(dirname,f)
Dir.chdir(dirname)
currDir=Dir.getwd
nf=0
nd=0
fs=0.0

if Dir.entries(currDir).size>2 then
Dir.foreach(currDir) {|x|
if FileTest.file?(x) && (Time.now-File.mtime(x))/(60*60*24)>15 then
f.puts("deleting file"+x)
nf=nf+1
fs=fs+File.stat(x).size
end
if FileTest.directory?(x) && x!="." && x!=".." then
lV=thisDir(x,f)
nf=nf+lV[0]
nd=nd+lV[1]
fs=fs+lV[2]
end
}
Dir.chdir("..")
end
if Dir.entries(currDir).size<=2 then
Dir.chdir("..")
f.puts("deleteting this directory:"+currDir)
nd=nd+1
#Dir.delete(currDir)
end

#Dir.chdir("..")
return [nf,nd,fs]
end
outFileName="cleaned-"+Date.today.to_s+".log"
f=File.new(outFileName,"w")
values=thisDir("./",f)
puts "Deleted "+values[0].to_s+" files"
puts "Deleted "+values[1].to_s+" directories"
puts "Total size deleted:"+(values[2]/(1024)).to_s+" kB"

Any advice is appriciated

--
Posted via http://www.ruby-....


1 Answer

Eero Saynatkari

1/22/2006 9:53:00 PM

0

FredrikC wrote:
> Hi!
> I'm designing (newbie level) a script to clean up empty directories and
> old files recursivly. Something is wrong..works fine when not actually
> deleting anything, but when I start removing files and directories it
> ends prematurly.. any heklp available..?
>
> def thisDir(dirname,f)
> Dir.chdir(dirname)
> currDir=Dir.getwd
> nf=0
> nd=0
> fs=0.0
>
> if Dir.entries(currDir).size>2 then
> Dir.foreach(currDir) {|x|
> if FileTest.file?(x) && (Time.now-File.mtime(x))/(60*60*24)>15 then
> f.puts("deleting file"+x)
> nf=nf+1
> fs=fs+File.stat(x).size
> end
> if FileTest.directory?(x) && x!="." && x!=".." then
> lV=thisDir(x,f)
> nf=nf+lV[0]
> nd=nd+lV[1]
> fs=fs+lV[2]
> end
> }
> Dir.chdir("..")
> end
> if Dir.entries(currDir).size<=2 then
> Dir.chdir("..")
> f.puts("deleteting this directory:"+currDir)
> nd=nd+1
> #Dir.delete(currDir)
> end
>
> #Dir.chdir("..")
> return [nf,nd,fs]
> end
> outFileName="cleaned-"+Date.today.to_s+".log"
> f=File.new(outFileName,"w")
> values=thisDir("./",f)
> puts "Deleted "+values[0].to_s+" files"
> puts "Deleted "+values[1].to_s+" directories"
> puts "Total size deleted:"+(values[2]/(1024)).to_s+" kB"
>
> Any advice is appriciated

I did not read this code yet but take a look at ri FileUtils,
it has useful methods including two that might be handy here:

FileUtils.rm_rf
FileUtils.mkdir_p


E

--
Posted via http://www.ruby-....