Skip to content

Instantly share code, notes, and snippets.

@rgm
Last active December 14, 2015 01:29
Show Gist options
  • Save rgm/5007050 to your computer and use it in GitHub Desktop.
Save rgm/5007050 to your computer and use it in GitHub Desktop.
Desktop file stasher, inspired by "Clean," see https://itunes.apple.com/ca/app/clean/id418412301?mt=12
#!/usr/bin/env ruby
# squirrel away src files into dst/YEAR-Month
# rename incoming file x.ext as x-1.ext if there's already x.ext in dst
# TODO getopts this stuff
source_folder = '~/Desktop'
destination_folder = "~/Documents/Crap/"
dry_run = false
verbose = true
#
# educational but terribly unnecessary functionalistic acrobatics follow
#
folder_name = ->(time) { time.strftime("%Y %B") }
src = File.expand_path source_folder
dst = File.expand_path File.join(destination_folder, folder_name[Time.now])
simple_rename = ->(path) { File.join dst, File.basename(path) }
exists = ->(renamer, path) { File.exist? renamer[path] }.curry
partition = ->(pred, ary) { [ary.select(&pred), ary.reject(&pred)] }
files = Dir[File.join(src,'*')].entries
exist_at_dst, do_not_exist_at_dst = partition.call(exists[simple_rename], files)
opts = { noop: dry_run, verbose: verbose }
mkdir_cmd = -> { FileUtils.mkdir_p dst, opts }
simple_mv_cmd = ->(path) { -> { FileUtils.mv path, simple_rename[path], opts } }
rename_with_number = ->(n, path) do
ext = File.extname path
base = File.basename path, ext
File.join dst, [base, "-", n, ext].join
end.curry
recursive_rename = ->(path, predicate, renamer, n) do
# TODO tail recur?
if predicate[renamer[n], path]
recursive_rename[path, predicate, renamer, n.succ]
else
renamer[n, path]
end
end
mv_rename_cmd = ->(path) do
-> { FileUtils.mv path,
recursive_rename[path, exists, rename_with_number, 1],
opts }
end
cmd_stream = []
cmd_stream << mkdir_cmd unless Dir.exists? dst
cmd_stream << do_not_exist_at_dst.map(&simple_mv_cmd)
cmd_stream << exist_at_dst.map(&mv_rename_cmd)
cmd_stream.flatten!
require 'FileUtils'
cmd_stream.map(&:call)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment