Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- require 'yaml'
- module LocaleTools
- module_function
- def flatten_keys(hash, prefix="", out_hash = {})
- keys = []
- hash.keys.each do |key|
- if hash[key].is_a? Hash
- current_prefix = prefix + "#{key}."
- keys << flatten_keys(hash[key], current_prefix, out_hash)
- else
- keys << "#{prefix}#{key}"
- out_hash["#{prefix}#{key}"] = hash[key]
- end
- end
- prefix == "" ? keys.flatten : keys
- end
- def compare(locale_1, locale_2, only_missing = false)
- yaml_1 = YAML.load(IO.read(locale_1))
- yaml_2 = YAML.load(IO.read(locale_2))
- h1 = {}
- h2 = {}
- keys_1 = flatten_keys(yaml_1[yaml_1.keys.first], "",h1)
- keys_2 = flatten_keys(yaml_2[yaml_2.keys.first], "",h2)
- if only_missing
- missing = keys_2 - keys_1
- missing.each { |key| puts "#{key}|#{h2[key]}" }
- else
- changed = keys_2.select{|k| h1[k] != h2[k] }
- changed.each { |key| puts "#{key}|#{h1[key]}|#{h2[key]}" }
- end
- end
- def patch(csv_file, locale_file)
- patch = {}
- IO.read(csv_file).each_line do |line|
- key, old, t9n = line.chomp.split("|")[0, 3]
- next unless key.to_s.index('.')
- patch[key] = t9n
- end
- data = YAML.load(IO.read(locale_file))
- root = data[data.keys.first]
- patch.each do |path, value|
- parts = path.split(".")
- node = root
- while parts.size > 1
- key = parts.shift
- node[key] ||= {}
- node = node[key]
- end
- node[parts.first] = value
- end
- print_yaml(data)
- end
- def print_yaml(hash, prefix="")
- hash.each do |k,v|
- if v.is_a? Hash
- puts prefix+k+":"
- print_yaml(v, prefix+" ")
- elsif v.nil?
- puts prefix+k+": ~"
- elsif v.is_a?(String)
- if v =~ /\n/
- puts prefix+k+": |-"
- v.split(/\n/).each do |line|
- puts prefix+" "+line
- end
- elsif v =~ /\s|[:,{}&%]/
- puts prefix+k+": "+v.inspect
- else
- puts prefix+k+": "+v
- end
- else
- puts prefix+k+": "+v.to_s
- end
- end
- end
- end
- if ARGV[0] == 'compare'
- # compare REVISION config/locales/en.yml > new_and_changed.csv
- `git show #{ARGV[1]}:#{ARGV[2]} >tmp/#{ARGV[1]}`
- LocaleTools.compare("tmp/#{ARGV[1]}", ARGV[2])
- elsif ARGV[0] == 'missing'
- # missing config/locales/en.yml config/locales/ru.yml > missing.csv
- LocaleTools.compare(ARGV[1], ARGV[2], true)
- elsif ARGV[0] == 'patch'
- # patch new_and_changed.csv confing/locales/ru.yml > ru-new.yml
- LocaleTools.patch(ARGV[1], ARGV[2])
- else
- puts <<-EOT
- t9n_tool: simple utility script to find missing and changed i18n keys in rails locale files, and apply batch translations from CSV
- Usage:
- script/t9n_tool missing config/locales/en.yml config/locales/ru.yml >missing.csv
- script/t9n_tool compare GIT_REVISION:config/locales/en.yml >new_and_changed.csv
- script/t9n_tool patch new_and_changed.csv config/locales/ru.yml >ru-new.yml
- EOT
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement