Skip to content

Instantly share code, notes, and snippets.

@jashmenn
Created February 14, 2009 01:44
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 jashmenn/64216 to your computer and use it in GitHub Desktop.
Save jashmenn/64216 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# organize_folder_by_date.rb
# by Nate Murray 2008. nate@natemurray.com
#
# == Description
# Organize all files in a given folder by date. This is commonly used to
# organize a "Downloads" folder.
#
# Currently, will only move files more than 24 hours old. This is to protect
# against moving a file as it is downloaded.
#
# == Motivation
# I love SafariStand:http://hetima.com/safari/stand-e.html . One of the
# features that I love is the sort-downloads-by-date feature. Now that I have
# moved to Firefox I really miss this feature. I haven't been able to find a
# good extension that will sort my downloads in a similar way. This script was
# written as an simple way to fill that gap.
#
# == Setup
# I keep a ~/bin directory where I keep simple scripts such as this. Then setup
# a crontab such as the following:
#
# */10 * * * * /usr/local/bin/ruby /Users/nathan/bin/organize_folder_by_date.rb /Users/nathan/Desktop/Downloads
#
# == Acquiring
# git clone git://github.com/jashmenn/download_sort.git
#
# == TODO
# * accept options for folder format
# * accept options for excludes
# * have age to move be an option
# * option for dry run
# * make an option to choose between file creation time or run-time
# * make a quiet option
# * sometimes downloads will unarchive a folder. currently this wont touch them. that is less than ideal
require 'rake'
unless ARGV.size == 1
puts "Usage: $0 folder"
exit(1)
end
format = "%F"
folder = ARGV[0]
FileList[folder + "/*"].each do |file|
# next if File.directory?(file)
next if File.basename(file) =~ /\d{4}\-\d{2}\-\d{2}/
created_at = File.ctime(file)
modified_at = File.mtime(file)
now = Time.now
# create the folder according to the creation date of the folder
time_to_use = modified_at # todo: make this an option
stamped_folder = File.join(folder, time_to_use.strftime(format))
# min_age = 60 * 60 * 24 # 24 hours in seconds
min_age = 60 * 60 * 3 # 3 hours in seconds
if (now - created_at).to_i > min_age
FileUtils.mkdir(stamped_folder, :verbose => true) unless File.exists?(stamped_folder)
FileUtils.mv(file, stamped_folder, :verbose => true)
else
# file is too young, just skip it
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment