Skip to content

Commit

Permalink
colons: Prevent error when space before is mandatory
Browse files Browse the repository at this point in the history
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:
#550 (comment)
  • Loading branch information
adrienverge committed Apr 5, 2023
1 parent e90e0a0 commit b92fc9c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
16 changes: 16 additions & 0 deletions tests/rules/test_colons.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,19 @@ def test_both_before_and_after(self):
' 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))
4 changes: 3 additions & 1 deletion yamllint/rules/colons.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@


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')
Expand Down

0 comments on commit b92fc9c

Please sign in to comment.