Search code examples
yamlruby-2.5

Why isn't two-spaced YAML parsed like four-spaced YAML?


I'm seeing strange behavior when parsing YAML (using Ruby 2.5/Psych) created using two space indentations. The same file, indented with four spaces per line works -- to my mind -- as expected.

Two spaces:

windows:
  - shell:
    panes:
      - echo hello

results in the following hash:

{"windows"=>[{"shell"=>nil, "panes"=>["echo hello"]}]}

Whereas using four space indentations:

windows:
    - shell:
        panes:
            - echo hello

results in:

{"windows"=>[{"shell"=>{"panes"=>["echo hello"]}}]}

I just skimmed through the spec and didn't see anything relevant to this issue.

Is this behavior expected? If so, I'd greatly appreciate links to resources explaining why.


Solution

  • The trouble is that you cannot simply replace every two spaces with four spaces. That is because in this pair of lines:

      - shell:
        panes:
    

    these two spaces in the second line:

        panes:
      ^^
    

    Are an abbrevation for the "- " in the line above. If the second line were not abbreviated, then the pair of lines would be:

      - shell:
      - panes:
    

    So when doubling the indentation, the second of these line should only have its first pair of spaces doubled, not the second. That would yield the correct indentation for the pair:

        - shell:
          panes:
    

    So, if you only expand the first pair of spaces in the "panes:" line, you get:

    windows:
        - shell:
          panes:
              - git status
    

    Which correctly parses to the expected result.