| 1 |
# Copyright: 2017, Ansible Project |
| 2 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause ) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import collections.abc as c |
| 7 |
|
| 8 |
from ansible.module_utils._internal import _no_six |
| 9 |
from ansible.module_utils.common.text.converters import to_text |
| 10 |
|
| 11 |
|
| 12 |
BOOLEANS_TRUE = frozenset(('y', 'yes', 'on', '1', 'true', 't', 1, 1.0, True)) |
| 13 |
BOOLEANS_FALSE = frozenset(('n', 'no', 'off', '0', 'false', 'f', 0, 0.0, False)) |
| 14 |
BOOLEANS = BOOLEANS_TRUE.union(BOOLEANS_FALSE) |
| 15 |
|
| 16 |
|
| 17 |
def boolean(value, strict=True): |
| 18 |
if isinstance(value, bool): |
| 19 |
return value |
| 20 |
|
| 21 |
normalized_value = value |
| 22 |
|
| 23 |
if isinstance(value, (str, bytes)): |
| 24 |
normalized_value = to_text(value, errors='surrogate_or_strict').lower().strip() |
| 25 |
|
| 26 |
if not isinstance(value, c.Hashable): |
| 27 |
normalized_value = None # prevent unhashable types from bombing, but keep the rest of the existing fallback/error behavior |
| 28 |
|
| 29 |
if normalized_value in BOOLEANS_TRUE: |
| 30 |
return True |
| 31 |
elif normalized_value in BOOLEANS_FALSE or not strict: |
| 32 |
return False |
| 33 |
|
| 34 |
raise TypeError("The value '%s' is not a valid boolean. Valid booleans include: %s" % (to_text(value), ', '.join(repr(i) for i in BOOLEANS))) |
| 35 |
|
| 36 |
|
| 37 |
def __getattr__(importable_name): |
| 38 |
return _no_six.deprecate(importable_name, __name__, "binary_type", "text_type") |