Skip to content

Commit

Permalink
ansible_module_utils: Add support for CaseInsensitive data types
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
rjeffman committed Dec 27, 2023
1 parent f6d3819 commit 12ecb03
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions plugins/module_utils/ansible_freeipa_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 12ecb03

Please sign in to comment.