Created
February 8, 2016 05:34
-
-
Save sunmockyang/f2de5ffbd6ee2b47b227 to your computer and use it in GitHub Desktop.
Takes all files recursively in a path and organizes based on date modified, puts them all into monthly folders
This file contains hidden or 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
| # File Archiver | |
| # Takes all files and organizes based on date modified | |
| # Puts them all into monthly folders | |
| # Usage: | |
| # ruby file-archiver.rb SRC_PATH [DEST_PATH] | |
| # If DEST_PATH isn't entered, then SRC_PATH will be used as destination | |
| require 'fileutils' | |
| root_dir = ARGV[0] | |
| out_dir = ARGV[1] | |
| if out_dir.nil? | |
| out_dir = root_dir | |
| end | |
| @use_separate_folder = root_dir != out_dir | |
| def archive_file(out_dir, f) | |
| mod_time = File.mtime(f) | |
| mod_year = mod_time.year | |
| mod_month = mod_time.month | |
| folder = "#{out_dir}/#{"%04d" % mod_year}-#{"%02d" % mod_month}" | |
| mkdir_p(folder) | |
| if f != "#{folder}/#{File.basename(f)}" | |
| if @use_separate_folder | |
| FileUtils.cp(f, "#{folder}/#{File.basename(f)}", :preserve => true, :verbose => true) | |
| else | |
| FileUtils.mv(f, "#{folder}/#{File.basename(f)}", :force => true, :verbose => true) | |
| end | |
| end | |
| end | |
| def delete_empty_dir(root_dir) | |
| recursive_dirs = Dir["#{root_dir}/**/*"].select { |f| File.directory?(f) } | |
| # Sort into deepest dirs first | |
| recursive_dirs = recursive_dirs.sort { |a, b| b.split("/").length - a.split("/").length } | |
| recursive_dirs.each { |d| | |
| if (Dir.entries(d) - %w[ . .. ]).empty? | |
| Dir.rmdir(d) | |
| end | |
| } | |
| end | |
| def mkdir_p(dir_path) | |
| Dir.mkdir(dir_path) unless File.exists?(dir_path) | |
| end | |
| mkdir_p(out_dir) | |
| Dir["#{root_dir}/**/*"].select{|f| File.file?(f)}.each { |f| | |
| archive_file(out_dir, f) | |
| } | |
| if @use_separate_folder | |
| delete_empty_dir(root_dir) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tested on osx