colons: Prevent error when space before is mandatory

In the rare case when the key before `:` is an alias (e.g. `{*x : 4}`),
the space before `:` is required (although this requirement is not
enforced by PyYAML), the reason being that a colon can be part of an
anchor name. Consequently, this commit adapts the `colons` rule to avoid
failures when this happens.

See this comment from Tina Müller for more details:
https://github.com/adrienverge/yamllint/pull/550#discussion_r1155297373
This commit is contained in:
Adrien Vergé 2023-04-04 18:44:26 +02:00
parent e90e0a0eb5
commit b92fc9cb31
2 changed files with 19 additions and 1 deletions

View File

@ -256,3 +256,19 @@ class ColonTestCase(RuleTestCase):
' property: {a: 1, b: 2, c : 3}\n', conf,
problem1=(3, 11), problem2=(4, 4),
problem3=(8, 23), problem4=(8, 28))
# Although accepted by PyYAML, `{*x: 4}` is not valid YAML: it should be
# noted `{*x : 4}`. The reason is that a colon can be part of an anchor
# name. See commit message for more details.
def test_with_alias_as_key(self):
conf = 'colons: {max-spaces-before: 0, max-spaces-after: 1}'
self.check('---\n'
'- anchor: &a key\n'
'- *a: 42\n'
'- {*a: 42}\n'
'- *a : 42\n'
'- {*a : 42}\n'
'- *a : 42\n'
'- {*a : 42}\n',
conf,
problem1=(7, 6), problem2=(8, 7))

View File

@ -92,7 +92,9 @@ DEFAULT = {'max-spaces-before': 0,
def check(conf, token, prev, next, nextnext, context):
if isinstance(token, yaml.ValueToken):
if isinstance(token, yaml.ValueToken) and not (
isinstance(prev, yaml.AliasToken) and
token.start_mark.pointer - prev.end_mark.pointer == 1):
problem = spaces_before(token, prev, next,
max=conf['max-spaces-before'],
max_desc='too many spaces before colon')