Skip to content

Instantly share code, notes, and snippets.

@carlosveucv
Last active June 1, 2022 09:52
Show Gist options
  • Save carlosveucv/780636d21a460b016f6853055143be61 to your computer and use it in GitHub Desktop.
Save carlosveucv/780636d21a460b016f6853055143be61 to your computer and use it in GitHub Desktop.
Replace values of a Yaml ( only if it exists and key (whole path) matches ) -> Generates a 3rd file
require 'yaml'
def hash_ypath(ypath, hash, value=nil)
paths = ypath.split('.', 2)
actual_path = paths[0]
return if hash[actual_path].nil?
if paths.size == 1
hash[actual_path] = value if value
return hash[actual_path]
end
return hash_ypath(paths[1], hash[actual_path], value)
end
@to_change = []
def compare_yaml_hash(cf1, cf2, context = [])
cf1.each do |key, value|
if !value.is_a?(Hash) && cf2.key?(key) && value != cf2[key]
ypath = "#{context.join(".")}.#{key}"
@to_change << {:path => ypath, :value => cf2[key]}
end
next unless cf2[key]
if value.is_a?(Hash)
compare_yaml_hash(value, cf2[key], (context + [key]))
next
end
end
end
f1 = ARGV[0]
f2 = ARGV[1]
yaml_hash = YAML.load_file(f1)
compare_yaml_hash(yaml_hash, YAML.load_file(f2))
@to_change.each do |change|
#puts "Path: #{change[:path]}, Value: #{change[:value]}"
hash_ypath(change[:path], yaml_hash, change[:value])
#puts hash_ypath(change[:path], yaml_hash)
end
f3 = ARGV[2]
File.open(f3, 'w') {|f| f.write yaml_hash.to_yaml }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment