Skip to content

Instantly share code, notes, and snippets.

@wteuber
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wteuber/c4cb1e4743a48ad24618 to your computer and use it in GitHub Desktop.
Save wteuber/c4cb1e4743a48ad24618 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# encoding: utf-8
require 'yaml'
require 'active_support/hash_with_indifferent_access'
class Hash
def self.new_from_hash_copying_default(hash)
hash = hash.to_hash
new(hash).tap do |new_hash|
new_hash.default = hash.default
end
end
def nested_under_indifferent_access
self
end
def with_indifferent_access
ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
end
def deep_merge(other_hash, &block)
dup.deep_merge!(other_hash, &block)
end
def deep_merge!(other_hash, &block)
other_hash.each_pair do |k,v|
tv = self[k]
if tv.is_a?(Hash) && v.is_a?(Hash)
self[k] = tv.deep_merge(v, &block)
else
self[k] = block && tv ? block.call(k, tv, v) : v
end
end
self
end
def to_hash_recursive
result = self.to_hash
result.each do |key, value|
case value
when Hash
result[key] = value.to_hash_recursive
when Array
result[key] = value.to_hash_recursive
end
end
result
end
def sort_by_key(recursive=false, &block)
self.keys.sort(&block).reduce({}) do |seed, key|
seed[key] = self[key]
if recursive && seed[key].is_a?(Hash)
seed[key] = seed[key].sort_by_key(true, &block)
end
seed
end
end
end
class Array
def to_hash_recursive
result = self
result.each_with_index do |value,i|
case value
when Hash
result[i] = value.to_hash_recursive
when Array
result[i] = value.to_hash_recursive
end
end
result
end
end
files = ARGV
files.sort!
files.uniq!
warn "Got:\n #{files*"\n"}"
yamls = {}
files.each { |file| raise "File not found: #{yaml}" unless File.exists? file }
files.each { |file| yamls[file] = YAML::load_file(file) }
files.each { |file| raise "File could not be parsed: #{file}" unless yamls[file].is_a? Hash }
files.each { |file| raise "More than 1 locale in one file: #{file}" unless yamls[file].keys.length == 1 }
result = {}
yamls.each do |file, yaml|
result.deep_merge! yaml
end
i18n_yaml = result.sort_by_key(true).to_yaml
process = i18n_yaml.split(/\n/).reject{|e| e == ''}[1..-1] # remove "---" from first line in yaml
# add an empty line if yaml tree level changes by 2 or more
tmp_ary = []
process.each_with_index do |line, idx|
tmp_ary << line
unless process[idx+1].nil?
this_line_spcs = line.match(/\A\s*/)[0].length
next_line_spcs = process[idx+1].match(/\A\s*/)[0].length
tmp_ary << '' if next_line_spcs - this_line_spcs < -2
end
end
puts tmp_ary * "\n"
warn "File(s) successfully merged.\n\n Output written to SDTOUT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment