Created
January 7, 2012 07:30
-
-
Save ahoward/1574108 to your computer and use it in GitHub Desktop.
convert files/directories to ensure utf8 marker.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
# encoding: utf-8 | |
# | |
# converts files to include a utf8 marker | |
# | |
# usage: utf8 files_or_directories | |
## | |
# | |
argv = ARGV.map{|arg| "#{ arg }"} | |
stdin = argv.delete('-') | |
argv.push(STDIN.readlines) if stdin | |
argv.flatten! | |
argv.compact! | |
argv.uniq! | |
files, directories = argv.partition{|arg| test(?f, arg)} | |
directories.each do |directory| | |
glob = File.join(File.expand_path(directory), '**/**') | |
Dir.glob(glob) do |entry| | |
files.push(File.expand_path(entry)) if test(?f, entry) | |
end | |
end | |
argv.flatten! | |
argv.compact! | |
argv.uniq! | |
## | |
# | |
utf_8 = "# encoding: utf-8" | |
files.each do |file| | |
head = [] | |
tail = [] | |
shebang = nil | |
had_encoding_line = false | |
open(file, 'r+') do |fd| | |
in_tail = false | |
fd.each do |line| | |
if in_tail | |
tail.push(line) | |
next | |
end | |
head.push(line) | |
is_blank = line.strip.empty? | |
is_shebang = line =~ /^\s*#\s*!/ | |
is_encoding = line =~ /^\s*#.*(encoding|coding)/ | |
if is_blank | |
next | |
end | |
if is_shebang | |
shebang ||= line | |
next | |
end | |
if is_encoding | |
had_encoding_line ||= line | |
next | |
end | |
in_tail = true | |
end | |
end | |
unless had_encoding_line | |
open(file, 'w') do |fd| | |
fd.puts(shebang) if shebang | |
fd.puts(utf_8) | |
fd.puts | |
fd.write(tail.join) | |
end | |
puts(file) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment