Created
October 27, 2010 09:55
-
-
Save animist/648758 to your computer and use it in GitHub Desktop.
File Collection Program by Date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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