Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add the ability to ignored keys while sorting #689

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
25 changes: 25 additions & 0 deletions tests/rules/test_key_ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,28 @@ def test_locale_accents(self):
'hais: true\n'
'haïr: true\n', conf,
problem=(3, 1))

def test_ignored_key(self):
conf = 'key-ordering:\n ignored: ["name"]'
self.check('---\n'
'versions:\n'
' - name: v1alpha1\n'
' foo: bar\n'
' - name: v2\n'
' baz: qux\n', conf)
self.check('---\n'
'versions:\n'
' - name: v1alpha1\n'
' foo: bar\n'
' baz: qux\n'
' - name: v2\n'
' baz: qux\n'
' - baz: qux\n'
' name: v3\n'
' value: whatever\n', conf,
problem=(5, 5))
self.check('---\n'
'age: 30\n'
'name: John\n'
'address: 123 Street\n', conf,
problem=(4, 1))
16 changes: 14 additions & 2 deletions yamllint/rules/key_ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
ordering is case-sensitive and not accent-friendly (see examples below).
This can be changed by setting the global ``locale`` option. This allows one
to sort case and accents properly.
It also allows one to ignore certain keys by setting the ``ignored`` option.

.. rubric:: Examples

Expand Down Expand Up @@ -78,6 +79,15 @@
haïr: true
hais: true
haïssable: true

#. With rule ``key-ordering: {ignored: ["name"]}``

the following code snippet would **PASS**:
::

- name: John
fernandezcuesta marked this conversation as resolved.
Show resolved Hide resolved
age: 30
city: New York
"""

from locale import strcoll
Expand All @@ -88,7 +98,8 @@

ID = 'key-ordering'
TYPE = 'token'

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't delete this line

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


Expand Down Expand Up @@ -118,7 +129,8 @@ def check(conf, token, prev, next, nextnext, context):
# sequences... strange, but allowed.
if len(context['stack']) > 0 and context['stack'][-1].type == MAP:
if any(strcoll(next.value, key) < 0
for key in context['stack'][-1].keys):
for key in context['stack'][-1].keys
if key not in conf['ignored']):
yield LintProblem(
next.start_mark.line + 1, next.start_mark.column + 1,
f'wrong ordering of key "{next.value}" in mapping')
Expand Down
Loading