There are two ruby on rails internationalization yaml files. One file is complete and another one is with missing keys. How can I compare two yaml files and see missing keys in second file? Are there any tools for doing that?
YAML Diff compares YAML, and because YAML is a a superset of JSON, it can compare JSON as well. In order to make the comparison meaningful, it formats the YAML, including sorting the keys, to then performs a texual comparison. YAML Diff is private and secure.
Loading a YAML Document Safely Using safe_load() safe_load(stream) Parses the given and returns a Python object constructed from the first document in the stream. safe_load recognizes only standard YAML tags and cannot construct an arbitrary Python object.
Spaces are allowed in keys according to the specification and for those you don't need quotes (double or single, each with their own use). It is just a scalar string containing a space.
The asterisk * means that all the endpoints that belongs to a certain category are either included or exluded. The sentence below just says that the asterisk * character must be quoted "*" in case of the YAML format usage over classic properties file.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With