How to compare keys in yaml files?
I couldn't find a fast tool to do that. I decided to write my own tool for this.
You can install it with cabal:
$ cabal update
$ cabal install yamlkeysdiff
Then you can diff two files this way:
$ yamlkeysdiff file1.yml file2.yml
> missing key in file2
< missing key in file1
You can also compare two subsets of the files:
$ yamlkeysdiff "file1.yml#key:subkey" "file2.yml#otherkey"
It behaves exactly like diff
, you can do this:
$ yamlkeysdiff file1.yml file2.yml && echo Is the same || echo Is different
differz compares two YAML files and prints missing keys in the second file.
differz show file1.yml file2.yml
It comes both as a library and as a command-line tool. You can install the latter with gem install differz
.
Assuming file1
is the proper version and file2
is the version with missing keys:
def compare_yaml_hash(cf1, cf2, context = [])
cf1.each do |key, value|
unless cf2.key?(key)
puts "Missing key : #{key} in path #{context.join(".")}"
next
end
value2 = cf2[key]
if (value.class != value2.class)
puts "Key value type mismatch : #{key} in path #{context.join(".")}"
next
end
if value.is_a?(Hash)
compare_yaml_hash(value, value2, (context + [key]))
next
end
if (value != value2)
puts "Key value mismatch : #{key} in path #{context.join(".")}"
end
end
end
Now
compare_yaml_hash(YAML.load_file("file1"), YAML.load_file("file2"))
Limitation: Current implementation should be extended to support arrays if your YAML file contains arrays.