Skip to content

Instantly share code, notes, and snippets.

@brianjlandau
Created July 29, 2010 01:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianjlandau/496953 to your computer and use it in GitHub Desktop.
Save brianjlandau/496953 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -KU
require 'optparse'
require 'ostruct'
require 'iconv'
SCRIPT_NAME = "File Character Encoding Converter"
SCRIPT_VERSION = "0.1"
class FileEncodingConverterOptionParser
def self.parse(args)
options = OpenStruct.new
options.to = 'UTF-8'
options.verbose = false
opts = OptionParser.new do |opts|
opts.banner = "Usage: convert_encoding.rb [options] directory|file..."
opts.separator ""
opts.separator "Specific options:"
opts.on("-f", "--from ENCODING", "Character Encoding converting from") do |encoding|
options.from = encoding
end
opts.on("-t", "--to ENCODING", "Character Encoding converting to") do |encoding|
options.to = encoding
end
opts.separator ""
opts.separator "Common options:"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options.verbose = v
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
opts.on_tail("-V", "--version", "Show version") do
puts SCRIPT_NAME + ' ' + SCRIPT_VERSION
exit
end
end
opts.parse!(args)
options
end
end
options = FileEncodingConverterOptionParser.parse(ARGV)
VERBOSE = options.verbose ? true : false
class FileEncodingConverter
def initialize(from, to = 'UTF-8')
@to = to
@from = from
end
def fconv(filename)
begin
contents = File.open(filename).read
output = Iconv.conv(@to, @from, contents)
file = File.open(filename, 'w')
file.write(output)
rescue Iconv::IllegalSequence
puts "Could not be processed: #{filename}"
else
if VERBOSE
puts "Processed successfully: #{filename}"
end
ensure
if defined? file
if file
file.close
file = nil
end
end
end
end
def process_dir(dir)
Dir.foreach(dir){ |filename|
if !filename.match(/^\./)
absolute_path = dir + '/' + filename
if File.file?(absolute_path)
self.fconv(absolute_path)
elsif File.directory?(absolute_path)
self.process_dir(absolute_path)
end
end
}
end
end
converter = FileEncodingConverter.new(options.from, options.to)
ARGV.each { |arg|
wd = Dir.getwd
entryname = arg.match(/^\//) ? wd + '/' + arg : arg
if File.directory?(entryname)
converter.process_dir(entryname)
elsif File.file?(entryname)
converter.fconv(entryname)
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment