Skip to content

Commit

Permalink
key-ordering: Add ignored-keys option
Browse files Browse the repository at this point in the history
This change allows ignoring certain keys by filling the `ignored-keys`
option with a list of PCRE regexes to select strings to ignore.
  • Loading branch information
adrienverge committed Mar 5, 2025
1 parent e427005 commit 2f87db8
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
22 changes: 22 additions & 0 deletions tests/rules/test_key_ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,25 @@ def test_locale_accents(self):
'hais: true\n'
'haïr: true\n', conf,
problem=(3, 1))

def test_ignored_keys(self):
conf = ('key-ordering:\n'
' ignored-keys: ["n(a|o)me", "^b"]\n')
self.check('---\n'
'a:\n'
'b:\n'
'c:\n'
'name: ignored\n'
'first-name: ignored\n'
'nome: ignored\n'
'gnomes: ignored\n'
'd:\n'
'e:\n'
'boat: ignored\n'
'.boat: ERROR\n'
'call: ERROR\n'
'f:\n'
'g:\n',
conf,
problem1=(12, 1),
problem2=(13, 1))
32 changes: 31 additions & 1 deletion yamllint/rules/key_ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@
This can be changed by setting the global ``locale`` option. This allows one
to sort case and accents properly.
.. rubric:: Options
* ``ignored-keys`` is a list of PCRE regexes to ignore some keys while checking
order, if they match any regex.
.. rubric:: Default values (when enabled)
.. code-block:: yaml
rules:
key-ordering:
ignored-keys: []
.. rubric:: Examples
#. With ``key-ordering: {}``
Expand Down Expand Up @@ -78,8 +91,21 @@
haïr: true
hais: true
haïssable: true
#. With rule ``key-ordering: {ignored-keys: ["name"]}``
the following code snippet would **PASS**:
::
- a:
b:
name: ignored
first-name: ignored
c:
d:
"""

import re
from locale import strcoll

import yaml
Expand All @@ -89,6 +115,8 @@
ID = 'key-ordering'
TYPE = 'token'

CONF = {'ignored-keys': [str]}
DEFAULT = {'ignored-keys': []}
MAP, SEQ = range(2)


Expand Down Expand Up @@ -116,7 +144,9 @@ def check(conf, token, prev, next, nextnext, context):
isinstance(next, yaml.ScalarToken)):
# This check is done because KeyTokens can be found inside flow
# sequences... strange, but allowed.
if len(context['stack']) > 0 and context['stack'][-1].type == MAP:
if (len(context['stack']) > 0 and context['stack'][-1].type == MAP and
not any(re.search(r, next.value)
for r in conf['ignored-keys'])):
if any(strcoll(next.value, key) < 0
for key in context['stack'][-1].keys):
yield LintProblem(
Expand Down

0 comments on commit 2f87db8

Please sign in to comment.