Created
May 9, 2014 21:21
-
-
Save jmeirow/bb4c9be368070aac5db3 to your computer and use it in GitHub Desktop.
fix scrambled files in Perforce
This file contains hidden or 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
require 'pp' | |
require 'fileutils' | |
class PerforceFileFix | |
def initialize open_files | |
@open_files = open_files | |
end | |
def self.utf_16_be_bom? file | |
begin | |
lines = IO.readlines(file) | |
return false if lines.nil? || lines.length == 0 | |
buffer = lines[0].each_byte.map{|x| x} | |
return (buffer[0] == 255 && buffer[1] == 254) | |
rescue Exception => e | |
puts file | |
end | |
end | |
def encode_line line, from_encoding, to_encoding | |
ec = Encoding::Converter.new(from_encoding, to_encoding, :universal_newline => true ) | |
dst = "" | |
ec.primitive_convert(line,dst) | |
dst | |
end | |
def write_line f, line | |
line = encode_line line, 'utf-16be', 'utf-16' | |
f.puts line | |
end | |
def write_first_line f, line | |
line = encode_line line,'utf-16', 'utf-16be' | |
f.puts line | |
end | |
def file_open? file | |
open = false | |
@open_files.each do |current_open_file| | |
open = true if current_open_file.include?(file) | |
break if open | |
end | |
open | |
end | |
def convert file | |
return if file_open?(file) | |
convert_file file | |
p4_edit file | |
copy_over file | |
p4_submit file | |
File.delete temp_file_name(file) | |
end | |
def copy_over file | |
FileUtils.copy_entry(temp_file_name(file), source_file(file), :remove_destinatation => true ) | |
end | |
def temp_file_name file | |
"./conversion/#{File.basename(file)}" | |
end | |
def source_file file | |
"./#{file}" | |
end | |
def convert_file file | |
File.open(temp_file_name(file), "w:UTF-16") do |f| | |
lines = IO.readlines(source_file(file)) | |
write_first_line(f,lines[0]) | |
(1..lines.length).each do |idx| | |
write_line(f,lines[idx]) | |
end | |
end | |
end | |
def p4_edit file | |
system("p4 edit -t utf16 #{file}") | |
end | |
def p4_submit file | |
message = %q("changed text type") | |
system( "p4 submit -d #{message} #{file}" ) | |
end | |
end | |
def desired_extension?file | |
['.sql', '.cfm', '.cs', '.rb', '.html', '.js', '.htm'].include?(File.extname(file)) | |
# ['.sql' ].include?(File.extname(file)) | |
end | |
def interesting_files | |
Dir.glob("**/*.*").map do |file| | |
next unless desired_extension?(file) | |
file | |
end | |
end | |
system('p4 opened -a //depot... > openfiles.txt') | |
open_files = IO.readlines('openfiles.txt') | |
File.delete('openfiles.txt') | |
interesting_files.each do |file| | |
puts "current#{file}" | |
if PerforceFileFix.utf_16_be_bom?(file) | |
PerforceFileFix.new(open_files).convert(file) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment