Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lint YAML files, preferably in Ruby

Tags:

ruby

yaml

How do I lint YAML files, without having to upload it to http://yamllint.com ?

For example, if I have

people:
  1:
    :name: John Smith
    :name: Jane Smith

How do I make it warn me that the last :name over-writes the first :name?

I'm using Ruby 2.1, and Ubuntu 12.04.

like image 992
Andrew Grimm Avatar asked Feb 07 '14 01:02

Andrew Grimm


People also ask

What is Linting in YAML?

A linter for YAML files. yamllint does not only check for syntax validity, but for weirdnesses like key repetition and cosmetic problems such as lines length, trailing spaces, indentation, etc.

What is a YAML file in Ruby?

Writing configuration files typically involves using the YAML data serialization language. YAML is an abbreviation that is a mark-up language, not a document. It is frequently employed in programs that store or transport data and configuration files. Data serialization is a feature of the YAML module in Ruby.


2 Answers

The yamllint command-line tool does what you want:

sudo pip install yamllint

Specifically, it has a rule key-duplicates that detects repetitions and keys over-writing one another:

$ yamllint test.yml
test.yml
  1:1       warning  missing document start "---"  (document-start)
  4:5       error    duplication of key ":name" in mapping  (key-duplicates)

(It has many other rules that you can enable/disable or tweak.)

like image 113
Adrien Vergé Avatar answered Oct 29 '22 20:10

Adrien Vergé


Is this what you're after?

require 'yaml'

def check_yaml(filename)
  unless YAML.dump(YAML.load_file(filename)) == File.read(filename).gsub(/\s*#.*/, '')
    raise 'problem' 
  end
end

check_yaml 'somefile.yml'
like image 44
seph Avatar answered Oct 29 '22 21:10

seph