From 12ecb03690795f23c9ce379ba4baf96677d04def Mon Sep 17 00:00:00 2001 From: Rafael Guterres Jeffman Date: Wed, 27 Dec 2023 15:51:58 -0300 Subject: [PATCH] ansible_module_utils: Add support for CaseInsensitive data types Add a cast function to create a string that can be compared in a case insensitive manner. It also allows the use of the objects in sets and dictionaries, making the key case insensitive. --- .../module_utils/ansible_freeipa_module.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/plugins/module_utils/ansible_freeipa_module.py b/plugins/module_utils/ansible_freeipa_module.py index 8926912565..ce1260a334 100644 --- a/plugins/module_utils/ansible_freeipa_module.py +++ b/plugins/module_utils/ansible_freeipa_module.py @@ -551,6 +551,34 @@ def ensure_fqdn(name, domain): return name +def CaseInsensitive(): # pylint: disable=invalid-name + """Create a case-insensitive string comparator.""" + def _converter(data): + class _CaseInsensitive(str): + # Operations rely on str.casefold(), as it may not be available, + # all calls are wrapped in a try-except block using str.lower as + # fallback. + def __hash__(self): + try: + _hash = hash(self.casefold()) + except Exception: # pylint: disable=broad-except + _hash = hash(self.lower()) + return _hash + + def __eq__(self, other): + if not isinstance(other, (str, _CaseInsensitive)): + other = to_text(other) + try: + _result = self.casefold() == other.casefold() + except Exception: # pylint: disable=broad-except + _result = self.lower() == other.lower() + return _result + + return _CaseInsensitive(data) + + return _converter + + def Service(realm): # pylint: disable=invalid-name def _converter(data): class _Service: