diff --git a/tests/rules/test_key_ordering.py b/tests/rules/test_key_ordering.py index 7d17603e..ddedcf8a 100644 --- a/tests/rules/test_key_ordering.py +++ b/tests/rules/test_key_ordering.py @@ -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)) diff --git a/yamllint/rules/key_ordering.py b/yamllint/rules/key_ordering.py index ec0716d9..ee1408e6 100644 --- a/yamllint/rules/key_ordering.py +++ b/yamllint/rules/key_ordering.py @@ -19,6 +19,21 @@ 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-keys`` +(PCRE regexes list) option. + +.. rubric:: Options + +* ``ignored-keys`` is a list of PCRE regexes defining a set of keys to be + ignored while ordering, if they match any regex. Default is an empty list. + +.. rubric:: Default values (when enabled) + +.. code-block:: yaml + + rules: + key-ordering: + ignored-keys: [] .. rubric:: Examples @@ -78,8 +93,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 @@ -89,6 +117,8 @@ ID = 'key-ordering' TYPE = 'token' +CONF = {'ignored-keys': [str]} +DEFAULT = {'ignored-keys': []} MAP, SEQ = range(2) @@ -116,7 +146,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(