Agefiles: Difference between revisions

From EggeWiki
mNo edit summary
mNo edit summary
 
Line 17: Line 17:
end.parse!
end.parse!


DIR = args[0] || '.'
if ARGV.size == 0 then
  raise("directory is required")
end
 
DIR = args[0]
File.directory?(DIR) || raise("#{DIR} is not a directory")
File.directory?(DIR) || raise("#{DIR} is not a directory")
MAXSIZE = case args[1]
MAXSIZE = case args[1]
when nil
when nil
   1000000
   1000000
when /([0-9]+)[Kk]B?/
when /^([0-9]+)[Kk]B?$/
   $1.to_i * 1024
   $1.to_i * 1024
when /([0-9]+)[mM]B?/
when /^([0-9]+)[mM]B?$/
   $1.to_i * 1024 * 1024
   $1.to_i * 1024 * 1024
when /([0-9]+)[gG]B?/
when /^([0-9]+)[gG]B?$/
   $1.to_i * 1024 * 1024 * 1024
   $1.to_i * 1024 * 1024 * 1024
when /^([0-9]+)$/
  $1.to_i
else
else
   $1.to_i
   raise("Invalid size #{args[1]}")
end
end


files = []
files = []

Latest revision as of 11:02, 21 July 2010

My script to delete old files

<geshi lang="ruby">

  1. !/bin/env ruby

require 'find' require 'optparse'

dryrun = false

args = OptionParser.new do |opts|

 opts.banner = "Usage: #{$0} [options] directory [size]"
 opts.on("-n", "--dry-run", "show what would have been deleted") do |v|
   dryrun = true
 end

end.parse!

if ARGV.size == 0 then

 raise("directory is required")

end

DIR = args[0] File.directory?(DIR) || raise("#{DIR} is not a directory") MAXSIZE = case args[1] when nil

 1000000

when /^([0-9]+)[Kk]B?$/

 $1.to_i * 1024

when /^([0-9]+)[mM]B?$/

 $1.to_i * 1024 * 1024

when /^([0-9]+)[gG]B?$/

 $1.to_i * 1024 * 1024 * 1024

when /^([0-9]+)$/

 $1.to_i

else

 raise("Invalid size #{args[1]}")

end

files = [] total = 0 Find.find(DIR) do |f|

 if File.file?(f) then
   files << [ File.mtime(f), File.size(f), f ]
   total += File.size(f)
 end

end

files = files.sort_by { |x| x[0] }

puts "#{DIR} is currently size #{total} and needs to be no more than #{MAXSIZE}" fcount=0 bcount=0 while total > MAXSIZE && (item = files.shift) do

 total -= item[1]
 bcount += item[1]
 if dryrun then
   puts "unlink #{item[2]}"
 else
   File.unlink(item[2])
 end
 fcount += 1

end

puts "deleted #{fcount} files totalling #{bcount} bytes" </geshi>