Skip to content

Instantly share code, notes, and snippets.

@mwilliammyers
Last active September 27, 2015 08:06
Show Gist options
  • Save mwilliammyers/cd565f5ed0448d5beef4 to your computer and use it in GitHub Desktop.
Save mwilliammyers/cd565f5ed0448d5beef4 to your computer and use it in GitHub Desktop.
Recursively (probably a bad idea) changes filename to the name of it's parent directory
#!/usr/bin/env ruby
require 'docopt'
require 'fileutils'
@app = File.basename(__FILE__).chomp('.rb')
@doc = <<DOCOPT
@app
Recursively (probably a bad idea) changes filename to the name of it's parent directory.
Copyright (C) 2015 William Myers https://github.com/mkwmms
Usage: #{@app} [options] FILE ...
Arguements:
FILE the file to change its name
Options:
-h --help show this help message and exit
-V --version show version and exit
-q --quiet suppress message output
-n --dry-run perform a trial run with no changes made
DOCOPT
def dry_run?
@args['--dry-run'] == true ? true : false
end
def verbose?
@args['--quiet'] == false || @args.nil? || dry_run? ? true : false
end
def info(title, *sput)
$stdout.puts "#{'==>'.blue} #{title}".bold
$stdout.puts sput if verbose?
end
def process_file(old_file)
info "#{dry_run? ? '(DRY-RUN) ' : ''}Processing: #{old_file}" if verbose?
old_dir = File.dirname(old_file)
ext = File.extname(old_file).downcase
dir_name = File.basename(old_dir)
dest_dir = File.dirname(old_dir)
new_file = File.join(dest_dir, "#{dir_name}#{ext}")
# TODO: don't overwrite existing files...
# TODO: move files to trash instead...
FileUtils.mv old_file, new_file, verbose: verbose?, noop: dry_run?
if Dir.entries(old_dir).size == 2
# Or recursively do it (but not in this method):
# Dir[File.join(dest_dir, '**/'].reverse_each { |d| Dir.rmdir d if Dir.entries(d).size == 2 }
FileUtils.rmdir old_dir, verbose: verbose?, noop: dry_run?
end
end
def main
@args = Docopt.docopt(@doc, version: "#{@app} 0.0.1")
@args['FILE'].each do |file|
file = File.expand_path(file)
if File.directory? file
files = File.join("#{file}/**", '*.*')
Dir[files].each do |f|
f = File.absolute_path(f)
process_file f
end
else
process_file file
end
end
rescue Docopt::Exit, RegexpError => e
puts e.message
end
main if $PROGRAM_NAME == __FILE__
# vim: tw=79 fenc=utf-8 ft=ruby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment