Skip to content

Instantly share code, notes, and snippets.

@jdar
Created January 7, 2013 03:06
Show Gist options
  • Save jdar/4472003 to your computer and use it in GitHub Desktop.
Save jdar/4472003 to your computer and use it in GitHub Desktop.
work in progress...
#!/usr/bin/env ruby
require 'rubygems'
require 'pathname'
require 'find'
begin
require 'debugger'
#TODO: why isn't this working?
$DEBUGGERON= ENV['DEBUGGER'].nil? ? true : eval(ENV['DEBUGGER'])
rescue LoadError => e
puts e.message
end
BINARY_FORMATS = 'ico|jpg|png|gif|jpeg|bmp|mpeg|mp3'.split("|").map{|f| f = "*."+f; [f.downcase,f.upcase] }.flatten
IGNORE_PATTERNS = BINARY_FORMATS+'ruby*sed*|*find_and_replace*|.git|.svn|README*|readme*|Gemfile.lock|vendor|gems'.split("|")
IGNORE_FILENAMES = '.git*|.svn|README*|readme*|Gemfile*|vendor|gems'.split("|")
replacements = {}
suggested_cmds = []
args = ARGV[1..-1]
raise "call with args regex:replace" unless args.any? and args.all?{|arg| arg.scan(/\:/).length == 1 }
args.collect!{|arg| arg.split ":" }
initial_path = Pathname.new(ARGV[0])
initial_path.find{ |p|
if IGNORE_PATTERNS.any?{|pattern| p.fnmatch? pattern }
puts "#ignoring #{p}"
Find.prune
end
new_contents = nil #scope fix
replacements.merge!(args.inject({}) do |acc,(k,v)|
k = k.start_with?("/") ? eval(k) : Regexp.new(k) # hacky regex
unless IGNORE_FILENAMES.any?{|pattern| p.basename.fnmatch? pattern }
suggested_cmds << "mv #{p} #{p.to_s.gsub k,v}" if p.basename.to_s[k]
end
break({}) if p.directory?
new_contents = p.read
if found = new_contents.gsub(k, v)
acc[p] ||= []
acc[p] <<(new_contents = found)
end
acc
end)
if $DEBUGGERON
puts "##{p}"
#debugger if replacements[p]
end
#COMMIT!
if initial_path.file?
p.open("w") {|f| f.truncate 0; f.write new_contents } if replacements[p]
else
#hirb?
#puts "#count: #{replacements[p].length}".rjust(60, "DEBUG=false #{__FILE__} #{p}")
puts "DEBUGGER=false ./#{__FILE__} #{p} #{ARGV[1..-1].join(" ")}"
end
}
puts "#found #{replacements.map{|k,v| [k.basename.to_s,v.length] }.inspect}"
puts "#total: #{replacements.inject(0){|acc,(k,v)| acc += v.length }}"
puts "note: filename suggestions only for first arg" if args[1]#.many?
puts "Suggestion commands to cleanup directory structure: \n#{suggested_cmds.join("\n")}" if suggested_cmds.any?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment