Skip to content

Instantly share code, notes, and snippets.

@animist
Created October 27, 2010 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save animist/648758 to your computer and use it in GitHub Desktop.
Save animist/648758 to your computer and use it in GitHub Desktop.
File Collection Program by Date
#!/usr/bin/env ruby
require 'optparse'
# Default parameters
from = Dir.pwd
dry = false
summary = <<EOT
File collection Program by Date
Usage: #{File::basename($0)} [options] target_directory
EOT
opts = OptionParser.new(summary)
opts.on("-f", "--from=VAL") do |v|
begin
if (File.directory?(v))
from = v
end
rescue
p $!
end
end
opts.on("-n", "--dry-run") do
dry = true
end
begin
opts.parse!
if (File.directory?(ARGV[0]))
to = ARGV[0]
else
throw "boo"
end
rescue
p $!
print opts.help
exit
end
Dir.foreach(from) do |file|
begin
fst = File.stat("#{from}/#{file}")
date = fst.mtime.strftime('%Y%m%d')
if fst.file?
mkdir = false
if File.directory?("#{to}/#{date}")
# do nothing
elsif File.exist?("#{to}/#{date}")
throw "File #{date} exists in #{to}"
else
mkdir = true
end
if dry
puts "try mkdir '#{to}/#{date}'." if mkdir
puts "try moving '#{from}/#{file}' -> '#{to}/#{date}'."
else
Dir.mkdir("#{to}/#{date}") if mkdir
File.rename("#{from}/#{file}", "#{to}/#{date}/#{file}")
end
end
rescue
p $!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment