| 1 |
# Copyright: (c) 2018, Sviatoslav Sydorenko <[email protected]> |
| 2 |
# Copyright: (c) 2018, Ansible Project |
| 3 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 4 |
"""Collection of low-level utility functions.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import collections.abc as _c |
| 9 |
import typing as _t |
| 10 |
|
| 11 |
from ansible.module_utils._internal import _no_six |
| 12 |
from ansible.module_utils.common import warnings as _warnings |
| 13 |
|
| 14 |
_KT = _t.TypeVar('_KT', bound=_c.Hashable) |
| 15 |
_VT = _t.TypeVar('_VT') |
| 16 |
_T = _t.TypeVar('_T', bound=_c.Hashable) |
| 17 |
|
| 18 |
|
| 19 |
class ImmutableDict(_c.Hashable, _c.Mapping[_KT, _VT], _t.Generic[_KT, _VT]): |
| 20 |
"""Dictionary that cannot be updated""" |
| 21 |
def __init__( |
| 22 |
self, |
| 23 |
*args: _c.Mapping[_KT, _VT] | _c.Iterable[tuple[_KT, _VT]], |
| 24 |
**kwargs: _VT, |
| 25 |
) -> None: |
| 26 |
self._store: dict[_KT, _VT] = dict(*args) if args else {} |
| 27 |
if kwargs: |
| 28 |
self._store.update(_t.cast(_c.Mapping[_KT, _VT], kwargs)) |
| 29 |
|
| 30 |
def __getitem__(self, key: _KT) -> _VT: |
| 31 |
return self._store[key] |
| 32 |
|
| 33 |
def __iter__(self) -> _c.Iterator[_KT]: |
| 34 |
return self._store.__iter__() |
| 35 |
|
| 36 |
def __len__(self) -> int: |
| 37 |
return self._store.__len__() |
| 38 |
|
| 39 |
def __hash__(self) -> int: |
| 40 |
return hash(frozenset(self.items())) |
| 41 |
|
| 42 |
def __eq__(self, other: object) -> bool: |
| 43 |
try: |
| 44 |
if self.__hash__() == hash(other): |
| 45 |
return True |
| 46 |
except TypeError: |
| 47 |
pass |
| 48 |
|
| 49 |
return False |
| 50 |
|
| 51 |
def __repr__(self) -> str: |
| 52 |
return 'ImmutableDict({0})'.format(repr(self._store)) |
| 53 |
|
| 54 |
def union(self, overriding_mapping: _c.Mapping[_KT, _VT]) -> ImmutableDict[_KT, _VT]: |
| 55 |
""" |
| 56 |
Create an ImmutableDict as a combination of the original and overriding_mapping |
| 57 |
|
| 58 |
:arg overriding_mapping: A Mapping of replacement and additional items |
| 59 |
:return: A copy of the ImmutableDict with key-value pairs from the overriding_mapping added |
| 60 |
|
| 61 |
If any of the keys in overriding_mapping are already present in the original ImmutableDict, |
| 62 |
the overriding_mapping item replaces the one in the original ImmutableDict. |
| 63 |
""" |
| 64 |
result = dict(self._store) |
| 65 |
result.update(overriding_mapping) |
| 66 |
return ImmutableDict(result) |
| 67 |
|
| 68 |
def difference(self, subtractive_iterable: _c.Iterable) -> ImmutableDict[_KT, _VT]: |
| 69 |
""" |
| 70 |
Create an ImmutableDict as a combination of the original minus keys in subtractive_iterable |
| 71 |
|
| 72 |
:arg subtractive_iterable: Any iterable containing keys that should not be present in the |
| 73 |
new ImmutableDict |
| 74 |
:return: A copy of the ImmutableDict with keys from the subtractive_iterable removed |
| 75 |
""" |
| 76 |
remove_keys = frozenset(subtractive_iterable) |
| 77 |
keys = (k for k in self._store.keys() if k not in remove_keys) |
| 78 |
return ImmutableDict((k, self._store[k]) for k in keys) |
| 79 |
|
| 80 |
|
| 81 |
class OrderedSet(_c.MutableSet[_T], _t.Generic[_T]): |
| 82 |
def __init__( |
| 83 |
self, |
| 84 |
iterable: _c.Iterable[_T] | None = None, |
| 85 |
/ |
| 86 |
) -> None: |
| 87 |
|
| 88 |
self._data: dict[_T, None] = dict.fromkeys(iterable or ()) |
| 89 |
|
| 90 |
def __repr__(self, /) -> str: |
| 91 |
return f'OrderedSet({list(self)!r})' |
| 92 |
|
| 93 |
def __eq__(self, other: object, /) -> bool: |
| 94 |
if not isinstance(other, OrderedSet): |
| 95 |
return NotImplemented |
| 96 |
return tuple(self._data) == tuple(other._data) |
| 97 |
|
| 98 |
def __contains__(self, x: object, /) -> bool: |
| 99 |
return x in self._data |
| 100 |
|
| 101 |
def __iter__(self, /) -> _c.Iterator[_T]: |
| 102 |
return self._data.__iter__() |
| 103 |
|
| 104 |
def __len__(self, /) -> int: |
| 105 |
return self._data.__len__() |
| 106 |
|
| 107 |
def add(self, value: _T) -> None: |
| 108 |
self._data[value] = None |
| 109 |
|
| 110 |
def discard(self, value: _T) -> None: |
| 111 |
self._data.pop(value, None) |
| 112 |
|
| 113 |
def clear(self) -> None: |
| 114 |
self._data.clear() |
| 115 |
|
| 116 |
def copy(self) -> OrderedSet[_T]: |
| 117 |
result: OrderedSet[_T] = OrderedSet() |
| 118 |
result._data = self._data.copy() |
| 119 |
return result |
| 120 |
|
| 121 |
def __and__(self, other: _c.Container, /) -> OrderedSet[_T]: |
| 122 |
# overridden, because the ABC produces an arguably unexpected sorting |
| 123 |
return OrderedSet(value for value in self if value in other) |
| 124 |
|
| 125 |
def __sub__(self, other: _c.Container, /) -> OrderedSet[_T]: |
| 126 |
return OrderedSet(value for value in self if value not in other) |
| 127 |
|
| 128 |
def __or__(self, other: _c.Set[_T], /) -> OrderedSet[_T]: # type: ignore[override] |
| 129 |
result = self.copy() |
| 130 |
for value in other: |
| 131 |
result._data[value] = None |
| 132 |
return result |
| 133 |
|
| 134 |
def __xor__(self, other: _c.Set[_T], /) -> OrderedSet[_T]: # type: ignore[override] |
| 135 |
result = self.copy() |
| 136 |
for value in other: |
| 137 |
if value in result._data: |
| 138 |
del result._data[value] |
| 139 |
else: |
| 140 |
result._data[value] = None |
| 141 |
return result |
| 142 |
|
| 143 |
def __rsub__(self, other: _c.Iterable[_T], /) -> OrderedSet[_T]: |
| 144 |
return OrderedSet(other).__sub__(self) |
| 145 |
|
| 146 |
def __rxor__(self, other: _c.Iterable[_T], /) -> OrderedSet[_T]: |
| 147 |
return OrderedSet(other).__xor__(self) |
| 148 |
|
| 149 |
difference = __sub__ |
| 150 |
difference_update = _c.MutableSet.__isub__ |
| 151 |
intersection = __and__ |
| 152 |
__rand__ = __and__ |
| 153 |
__ror__ = __or__ |
| 154 |
intersection_update = _c.MutableSet.__iand__ |
| 155 |
issubset = _c.MutableSet.__le__ |
| 156 |
issuperset = _c.MutableSet.__ge__ |
| 157 |
symmetric_difference = __xor__ |
| 158 |
symmetric_difference_update = _c.MutableSet.__ixor__ |
| 159 |
union = __or__ |
| 160 |
update = _c.MutableSet.__ior__ |
| 161 |
|
| 162 |
|
| 163 |
def is_string(seq: _c.Iterable) -> bool: |
| 164 |
"""Identify whether the input has a string-like type (including bytes).""" |
| 165 |
return isinstance(seq, (str, bytes)) |
| 166 |
|
| 167 |
|
| 168 |
def is_iterable(seq: _c.Iterable, include_strings: bool = False) -> bool: |
| 169 |
"""Identify whether the input is an iterable.""" |
| 170 |
if not include_strings and is_string(seq): |
| 171 |
return False |
| 172 |
|
| 173 |
try: |
| 174 |
iter(seq) |
| 175 |
return True |
| 176 |
except TypeError: |
| 177 |
return False |
| 178 |
|
| 179 |
|
| 180 |
def is_sequence(seq: _c.Iterable, include_strings: bool = False) -> bool: |
| 181 |
"""Identify whether the input is a sequence. |
| 182 |
|
| 183 |
Strings and bytes are not sequences here, |
| 184 |
unless ``include_string`` is ``True``. |
| 185 |
|
| 186 |
Non-indexable things are never of a sequence type. |
| 187 |
""" |
| 188 |
if not include_strings and is_string(seq): |
| 189 |
return False |
| 190 |
|
| 191 |
return isinstance(seq, _c.Sequence) |
| 192 |
|
| 193 |
|
| 194 |
def count(seq: _c.Iterable) -> dict[_c.Hashable, int]: |
| 195 |
"""Returns a dictionary with the number of appearances of each element of the iterable. |
| 196 |
|
| 197 |
Resembles the collections.Counter class functionality. It is meant to be used when the |
| 198 |
code is run on Python 2.6.* where collections.Counter is not available. It should be |
| 199 |
deprecated and replaced when support for Python < 2.7 is dropped. |
| 200 |
""" |
| 201 |
_warnings.deprecate( |
| 202 |
msg="The `ansible.module_utils.common.collections.count` function is deprecated.", |
| 203 |
version="2.23", |
| 204 |
help_text="Use `collections.Counter` from the Python standard library instead.", |
| 205 |
) |
| 206 |
if not is_iterable(seq): |
| 207 |
raise Exception('Argument provided is not an iterable') |
| 208 |
counters: dict[_c.Hashable, int] = {} |
| 209 |
for elem in seq: |
| 210 |
counters[elem] = counters.get(elem, 0) + 1 |
| 211 |
return counters |
| 212 |
|
| 213 |
|
| 214 |
Hashable = _c.Hashable |
| 215 |
Mapping = _c.Mapping |
| 216 |
MutableMapping = _c.MutableMapping |
| 217 |
Sequence = _c.Sequence |
| 218 |
|
| 219 |
|
| 220 |
def __getattr__(importable_name): |
| 221 |
return _no_six.deprecate(importable_name, __name__, "binary_type", "text_type") |