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

truthy rule: add check-keys option #247

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions tests/rules/test_truthy.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,29 @@ def test_explicit_types(self):
'boolean5: !!bool off\n'
'boolean6: !!bool NO\n',
conf)

def test_check_keys_disabled(self):
conf = ('truthy:\n'
' allowed-values: []\n'
' check-keys: false\n'
'key-duplicates: disable\n')
self.check('---\n'
'YES: 0\n'
'Yes: 0\n'
'yes: 0\n'
'No: 0\n'
'No: 0\n'
'no: 0\n'
'TRUE: 0\n'
'True: 0\n'
'true: 0\n'
'FALSE: 0\n'
'False: 0\n'
'false: 0\n'
'ON: 0\n'
'On: 0\n'
'on: 0\n'
'OFF: 0\n'
'Off: 0\n'
'off: 0\n',
ilyam8 marked this conversation as resolved.
Show resolved Hide resolved
conf)
27 changes: 25 additions & 2 deletions yamllint/rules/truthy.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
``'False'``, ``'false'``, ``'YES'``, ``'Yes'``, ``'yes'``, ``'NO'``,
``'No'``, ``'no'``, ``'ON'``, ``'On'``, ``'on'``, ``'OFF'``, ``'Off'``,
``'off'``.
* ``check-keys`` disables verification for keys in mappings. By default,
``truthy`` rule applies to both keys and values. Set this option to ``false``
to prevent this.

.. rubric:: Examples

Expand Down Expand Up @@ -92,6 +95,22 @@
- false
- on
- off

#. With ``truthy: {check-keys: false}``

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

yes: 1
on: 2
true: 3

the following code snippet would **FAIL**:
::

yes: Yes
on: On
true: True
"""

import yaml
Expand All @@ -109,14 +128,18 @@

ID = 'truthy'
TYPE = 'token'
CONF = {'allowed-values': list(TRUTHY)}
DEFAULT = {'allowed-values': ['true', 'false']}
CONF = {'allowed-values': list(TRUTHY), 'check-keys': bool}
DEFAULT = {'allowed-values': ['true', 'false'], 'check-keys': True}


def check(conf, token, prev, next, nextnext, context):
if prev and isinstance(prev, yaml.tokens.TagToken):
return

if (not conf['check-keys'] and isinstance(prev, yaml.tokens.KeyToken) and
isinstance(token, yaml.tokens.ScalarToken)):
return

if isinstance(token, yaml.tokens.ScalarToken):
if (token.value in (set(TRUTHY) - set(conf['allowed-values'])) and
token.style is None):
Expand Down