14

I'm using the following linter to check if my yml is valid: http://www.yamllint.com/

I tried putting inline comments, but they are removed. I read the spec here http://www.yaml.org/spec/1.2/spec.html#id2780069

Am I correct that the following is actually valid and that the linting website is wrong by removing the comments?

cache: 
  paths: 
    - node_modules/ # some comment here
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
basickarl
  • 37,187
  • 64
  • 214
  • 335
  • 1
    The linter says that the yml is valid. The linter probably just removes comments by default. It doesn't say that it's not valid. – Cave Johnson Jun 16 '17 at 07:46
  • @KodosJohnson You are indeed correct, I rephrased the sentence. However the linter shouldn't be removing the comments don't you think? – basickarl Jun 16 '17 at 07:51
  • My theory is that a parser reads the yml to determine its validity and then rebuilds the yml to display back to you. As part of the process the parser discards any comments since they don't have any effect (they are just comments and not meant to be used by the parser). So I think it is just a side effect. – Cave Johnson Jun 16 '17 at 07:56
  • Related (see the answers): *[How do you do block comments in YAML?](https://stackoverflow.com/questions/2276572/how-do-you-do-block-comments-in-yaml/60238027#60238027)* – Peter Mortensen Dec 13 '22 at 22:55

1 Answers1

9

Your source is correct. If you want to run such a check with preservation of the comments, or reformat preserving the comments, then use a small Python program based on ruamel.yaml, which can preserve your comments on round-trip and normalize the indentation (disclaimer: I am author of ruamel.yaml):

import sys
from ruamel.yaml import YAML
from ruamel.yaml.util import load_yaml_guess_indent
    
with open(sys.argv[1]) as fp:
    data, ind, offset = load_yaml_guess_indent(fp)
yaml = YAML()
yaml.indent(mapping=ind, sequence=ind, offset=offset)
yaml.dump(data, sys.stdout)

just provide the input file as parameter on the commandline.

This has the advantage over all web based checkers that your possible sensitive data doesn't get "published". It also has the advantage over yamllint.com and some other sites, that it supports YAML 1.2. yamllint.com only supports YAML 1.1, what you can see if you try it with an explicit YAML document directive:

%YAML 1.2
--- 
a: 0o7
...

That site throws an error that that version is not supported. Which is better than what e.g. http://yaml-online-parser.appspot.com/ does (directive ignored, parsed as if YAML 1.1, with the octal integer scalar as if it where a string scalar) or the half-fledged implementation of YAML at http://beautifytools.com/yaml-validator.php (Error: unable to parse))

Anthon
  • 69,918
  • 32
  • 186
  • 246