Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In yaml are spaces accepted between a key and its colon?

For example, from a docker compose file

services:
    cool:
        container_name: coolas
        image         : repo/cool:latest
        restart       : unless-stopped
        ports         : 
            - "6060:6060"

YAMLint says "Valid YAML!". Docker compose hasn't complained.

There's many questions about spaces or lack thereof after the colon, and some within the key, or escaping colons in the value. There's many examples of yaml, but I didn't find any with spaces before the colon.

I like lining things up generally, and with syntax colouring it becomes easier to spot something out of place. But I worry that since no-one seems to do it, maybe it's a bad idea.

like image 544
JohnLittle Avatar asked Oct 20 '25 01:10

JohnLittle


1 Answers

A key-value pair in a block mapping is a ns-l-block-map-implicit-entry(n) in the grammar, where the key is a ns-l-block-map-implicit-key, which can be either one of these:

[154] ns-s-implicit-yaml-key(c) ::=
  ns-flow-yaml-node(0,c)
  s-separate-in-line?
  /* At most 1024 characters altogether */
[155] c-s-implicit-json-key(c) ::=
  c-flow-json-node(0,c)
  s-separate-in-line?
  /* At most 1024 characters altogether */

s-separate-in-line allows whitespace, hence there is whitespace allowed after the key, before the : that starts the value.

Whether it's a good idea or not is generally opinion-based. I would say, whitespace should either be structuring or styling, not both. A lot of whitespace that is only used for aligning items might be misread as indentation and thus makes the YAML harder to read. If I wanted to align : in my YAML, I would, for this reason, use YAML flow style where indentation is not structuring:

{
  services: {
    cool: {
      container_name: coolas,
      image         : repo/cool:latest,
      restart       : unless-stopped,
      ports         : ["6060:6060"],
    },
  },
}

Of course, this re-introduces some JSON-like noise, which might have been the reason to use YAML in the first place.

Another relevant question would be whether you want or should use a code prettifier that makes that decision for you anyway. The merit from code prettifiers grows with the amount of people in the project.

like image 190
flyx Avatar answered Oct 22 '25 04:10

flyx