Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare keys in yaml files?

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?

like image 882
Jonas Avatar asked Jun 08 '11 04:06

Jonas


People also ask

How do I compare two YAML files?

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.

What is YAML Safe_load?

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.

Can YAML keys have spaces?

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.

What does asterisk mean in YAML?

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.


2 Answers

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.

like image 187
Harish Shetty Avatar answered Oct 09 '22 01:10

Harish Shetty


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
like image 25
Antoine Catton Avatar answered Oct 09 '22 00:10

Antoine Catton