1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- require 'csv'
- require 'nokogiri'
- module MultiLangTrans
- class << self
- INPUT_FOLDER = 'input/*.csv'
- TEMPLATE_FOLDER = 'template/*.resw'
- TEMPLATE_CSV_PATH = 'template/template.csv'
- def run
- template_file_paths = Dir.glob(TEMPLATE_FOLDER)
- print "Using #{template_file_paths.first}, "
- make_template(template_file_paths.first)
- input_file_paths = Dir.glob(INPUT_FOLDER)
- puts "#{input_file_paths.count} file(s) translating..."
- input_file_paths.each do |input_file_path|
- input_content = read_csv(input_file_path)
- output_file_paths = get_output_paths(input_file_path)
- print " * #{input_file_path} --> #{output_file_paths[:matched]}, #{output_file_paths[:dismatched]}: "
- puts 'ok!' if write_xml(output_file_paths, input_content)
- end
- puts 'Done!'
- end
- private
- def make_template(template_file_path)
- xml_doc = File.open(template_file_path) { |f| Nokogiri::XML(f) }
- File.open(TEMPLATE_CSV_PATH, 'w') do |f|
- f.puts("name,trans_value,trans_comment")
- xml_doc.xpath("//data").each do |data|
- value = data.at_xpath('value').content unless data.at_xpath('value').nil?
- comment = data.at_xpath('comment').content unless data.at_xpath('comment').nil?
- f.puts("#{data['name']},#{value},#{comment}")
- end
- end
- @template_content = read_csv(TEMPLATE_CSV_PATH)
- end
- def read_csv(csv_file_path)
- input_content = []
- CSV.foreach(csv_file_path, headers: true) do |row|
- input_content << row.to_hash
- end
- input_content
- end
- def get_output_paths(input_path)
- output_paths = {}
- output_path = input_path.sub('input/', "output/")
- output_paths[:matched] = output_path.sub('.csv', ".txt")
- output_paths[:dismatched] = output_path.sub('.csv', "-not-found.txt")
- output_paths
- end
- def write_xml(xml_file_paths, content_rows)
- not_found_rows = []
- File.open(xml_file_paths[:matched], 'w') do |f|
- content_rows.each_with_index do |row, index|
- template_row = @template_content.find{|t| t['trans_value'] == row['template_value']}
- if template_row.nil?
- not_found_rows << "line:#{index + 2}.\t#{row['template_value']}"
- else
- f.puts("<trans-unit id=\"#{template_row['name']}\" translate=\"yes\" xml:space=\"preserve\">")
- f.puts(" <source>#{template_row['trans_value']}</source>") unless template_row['trans_value'].nil?
- f.puts(" <target state=\"translated\">#{row['trans_value']}</target>") unless row['trans_value'].nil?
- f.puts(" <note from=\"MultilingualBuild\" annotates=\"source\" priority=\"2\">#{template_row['trans_comment']}</note>") unless template_row['trans_comment'].nil?
- f.puts("</trans-unit>")
- end
- end
- end
- File.open(xml_file_paths[:dismatched], 'w') do |f|
- not_found_rows.each { |row| f.puts(row) }
- end
- true
- rescue => e
- puts e
- false
- end
- end
- end
- MultiLangTrans.run
|