Skip to content

Instantly share code, notes, and snippets.

@bogdan
Created April 22, 2013 13:42
Show Gist options
  • Select an option

  • Save bogdan/5434953 to your computer and use it in GitHub Desktop.

Select an option

Save bogdan/5434953 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rubygems'
require "active_support/inflector"
require "optparse"
class Rsub
def self.run(args)
self.new(args).run
end
def initialize(args)
@options = {}
options[:replace] = true
options[:rename] = true
@option_parser = OptionParser.new do |opts|
opts.banner = "Rename files and pattern in file"
opts.on("-a", "--all", "Same as -cusp") do
options[:underscore] = true
options[:camelize] = true
options[:singularize] = true
options[:pluralize] = true
end
opts.on("-u", "--underscore", "Use underscore conversion for specified pattern") do
options[:underscore] = true
end
opts.on("-c", "--camelcase", "Use camelcase conversion for specified pattern") do
options[:camelize] = true
end
opts.on("-s", "--singular", "Use singular conversion for specified pattern") do
options[:singularize] = true
end
opts.on("-p", "--plural", "Use plural conversion for specified pattern") do
options[:plural] = true
end
opts.on("-f", "--files", "Only rename files") do
options[:rename] = true
options[:replace] = false unless options.has_key?(:replace)
end
opts.on("-r", "--replace", "Only replace file content") do
options[:replace] = true
options[:rename] = false unless options.has_key?(:rename)
end
end
@option_parser.parse!(args)
if args.size < 3
usage
exit 1
end
@old_name = args.shift
@new_name = args.shift
@path = args.join(" ")
end
def run
pairs.each do |from, to|
rename_files(from, to) if options[:rename]
replace(from, to) if options[:replace]
end
end
protected
def pairs
@pairs ||= (
if only?
{@old_name => @new_name}
else
result = {}
[options[:pluralize] && :pluralize, options[:singularize] && :singularize].each do |amount|
[options[:underscore] && :underscore, options[:camelize] && :camelize].each do |wordcase|
if wordcase && amount
result[@old_name.send(wordcase).send(amount)] = @new_name.send(wordcase).send(amount)
end
end
end
result
end
)
end
def rename_files(from, to)
files = exec("find #{@path} -name '#{from}*' ").split("\n")
files.each do |old_name|
new_name = old_name.gsub(from, to)
exec "mv -v #{old_name} #{new_name}"
end
end
def replace(from, to)
exec "find #{@path} -type f -exec #{sed_command} 's/#{from}/#{to}/g' {} \\;"
end
def sed_command
[
"sed",
"-i",
macos? ? "''" : "",
].join(" ")
end
def macos?
RUBY_PLATFORM.include?("darwin")
end
def exec(command)
puts command
`#{command}`
end
def usage
puts <<-EOI
Usage: rsub [-acusp] <oldname> <newname> <path> [<path> ...]
EOI
@option_parser.display
end
def only?
!(options[:underscore] || options[:camelize] || options[:singularize] || options[:plural])
end
def options
@options
end
end
Rsub.run(ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment