Skip to content

Instantly share code, notes, and snippets.

@msuarz
Last active August 29, 2015 14:05
Show Gist options
  • Save msuarz/9425e136663fdfd39072 to your computer and use it in GitHub Desktop.
Save msuarz/9425e136663fdfd39072 to your computer and use it in GitHub Desktop.
music folder cleanup
#encoding: IBM437
require 'rake'
require 'fileutils'
task :clean, :folder do |t, args|
Music.new(args.to_hash).cleanup
end
task :biggie, :folder do |t, args|
Music.new(args.to_hash).show_by_size
end
class Music
attr_reader :root
def initialize opts
@root = opts[:folder]
end
def cleanup
cleanup_files
cleanup_empty_folders
show_weird_names
end
def show_by_size
sort(biggie).each { |x| show x }
sort(smalls).each { |x| show x }
end
def cleanup_files
puts 'no dirty files found!!' if dirty_files.empty?
dirty_files.each do |crap|
FileUtils.remove_file crap, true
puts "bye bye #{crap}"
end
end
def cleanup_empty_folders
puts 'no empty folders found!!' if empty_dirs.empty?
until empty_dirs.empty?
empty_dirs.each do |x|
FileUtils.remove_dir x, true
puts "bye bye #{x}"
end
end
end
def show_weird_names
puts 'no weird names found!!' if weird_names.empty?
weird_names.each do |x|
puts x
puts fix_name x
end
end
def all; Dir["#{root}/**/*"] end
def all_dirs; all.select { |x| File.directory? x } end
def empty_dirs; all_dirs.select { |x| Dir.entries(x).length == 2 } end
def dir_sizes; @dir_sizes ||= `du #{root} --max-depth=1 -h`.lines end
def biggie; dir_sizes.select { |x| x.split[0].end_with? 'G' } end
def smalls; dir_sizes.select { |x| x.split[0].end_with? 'M' } end
def size dir; dir.split[0].to_f end
def sort dirs; dirs.sort_by { |x| -size(x) } end
def show dir; puts dir.gsub /#{root}\//, '' end
def dirty_files; @dirty_files ||= (all_files - mp3s) end
def all_files; all.reject { |x| File.directory? x } end
def mp3s; Dir["#{root}/**/*.mp3"] end
WEIRD = /[^\p{Alnum}\p{Space}\.\/\-&'\[\]\(\)\!\+_,#%^\$\@~\?\{\};`\=ëöüáéíóâñè]/
def weird_names; all.select { |x| is_weird? x } end
def is_weird? x; x.match WEIRD end
def fix_name x; x.gsub WEIRD, '' end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment