| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright (c) 2019 Ansible Project |
| 3 |
# (c) 2016 Toshio Kuratomi <[email protected]> |
| 4 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import codecs |
| 9 |
import json |
| 10 |
|
| 11 |
from ansible.module_utils.compat import typing as _t |
| 12 |
from ansible.module_utils._internal import _no_six |
| 13 |
|
| 14 |
try: |
| 15 |
codecs.lookup_error('surrogateescape') |
| 16 |
HAS_SURROGATEESCAPE = True |
| 17 |
except LookupError: |
| 18 |
HAS_SURROGATEESCAPE = False |
| 19 |
|
| 20 |
|
| 21 |
_COMPOSED_ERROR_HANDLERS = frozenset((None, 'surrogate_or_replace', |
| 22 |
'surrogate_or_strict', |
| 23 |
'surrogate_then_replace')) |
| 24 |
|
| 25 |
_T = _t.TypeVar('_T') |
| 26 |
|
| 27 |
_NonStringPassthru: _t.TypeAlias = _t.Literal['passthru'] |
| 28 |
_NonStringOther: _t.TypeAlias = _t.Literal['simplerepr', 'empty', 'strict'] |
| 29 |
_NonStringAll: _t.TypeAlias = _t.Union[_NonStringPassthru, _NonStringOther] |
| 30 |
|
| 31 |
|
| 32 |
@_t.overload |
| 33 |
def to_bytes( |
| 34 |
obj: object, |
| 35 |
encoding: str = 'utf-8', |
| 36 |
errors: str | None = None, |
| 37 |
) -> bytes: ... |
| 38 |
|
| 39 |
|
| 40 |
@_t.overload |
| 41 |
def to_bytes( |
| 42 |
obj: bytes | str, |
| 43 |
encoding: str = 'utf-8', |
| 44 |
errors: str | None = None, |
| 45 |
nonstring: _NonStringPassthru = 'passthru', |
| 46 |
) -> bytes: ... |
| 47 |
|
| 48 |
|
| 49 |
@_t.overload |
| 50 |
def to_bytes( |
| 51 |
obj: _T, |
| 52 |
encoding: str = 'utf-8', |
| 53 |
errors: str | None = None, |
| 54 |
nonstring: _NonStringPassthru = 'passthru', |
| 55 |
) -> _T: ... |
| 56 |
|
| 57 |
|
| 58 |
@_t.overload |
| 59 |
def to_bytes( |
| 60 |
obj: object, |
| 61 |
encoding: str = 'utf-8', |
| 62 |
errors: str | None = None, |
| 63 |
nonstring: _NonStringOther = 'simplerepr', |
| 64 |
) -> bytes: ... |
| 65 |
|
| 66 |
|
| 67 |
def to_bytes( |
| 68 |
obj: _T, |
| 69 |
encoding: str = 'utf-8', |
| 70 |
errors: str | None = None, |
| 71 |
nonstring: _NonStringAll = 'simplerepr' |
| 72 |
) -> _T | bytes: |
| 73 |
"""Make sure that a string is a byte string |
| 74 |
|
| 75 |
:arg obj: An object to make sure is a byte string. In most cases this |
| 76 |
will be either a text string or a byte string. However, with |
| 77 |
``nonstring='simplerepr'``, this can be used as a traceback-free |
| 78 |
version of ``str(obj)``. |
| 79 |
:kwarg encoding: The encoding to use to transform from a text string to |
| 80 |
a byte string. Defaults to using 'utf-8'. |
| 81 |
:kwarg errors: The error handler to use if the text string is not |
| 82 |
encodable using the specified encoding. Any valid `codecs error |
| 83 |
handler <https://docs.python.org/3/library/codecs.html#codec-base-classes>`_ |
| 84 |
may be specified. There are three additional error strategies |
| 85 |
specifically aimed at helping people to port code. The first two are: |
| 86 |
|
| 87 |
:surrogate_or_strict: Will use ``surrogateescape`` if it is a valid |
| 88 |
handler, otherwise it will use ``strict`` |
| 89 |
:surrogate_or_replace: Will use ``surrogateescape`` if it is a valid |
| 90 |
handler, otherwise it will use ``replace``. |
| 91 |
|
| 92 |
Because ``surrogateescape`` was added in Python3 this usually means that |
| 93 |
Python3 will use ``surrogateescape`` and Python2 will use the fallback |
| 94 |
error handler. Note that the code checks for ``surrogateescape`` when the |
| 95 |
module is imported. If you have a backport of ``surrogateescape`` for |
| 96 |
Python2, be sure to register the error handler prior to importing this |
| 97 |
module. |
| 98 |
|
| 99 |
The last error handler is: |
| 100 |
|
| 101 |
:surrogate_then_replace: Will use ``surrogateescape`` if it is a valid |
| 102 |
handler. If encoding with ``surrogateescape`` would traceback, |
| 103 |
surrogates are first replaced with a replacement characters |
| 104 |
and then the string is encoded using ``replace`` (which replaces |
| 105 |
the rest of the nonencodable bytes). If ``surrogateescape`` is |
| 106 |
not present it will simply use ``replace``. (Added in Ansible 2.3) |
| 107 |
This strategy is designed to never traceback when it attempts |
| 108 |
to encode a string. |
| 109 |
|
| 110 |
The default until Ansible-2.2 was ``surrogate_or_replace`` |
| 111 |
From Ansible-2.3 onwards, the default is ``surrogate_then_replace``. |
| 112 |
|
| 113 |
:kwarg nonstring: The strategy to use if a nonstring is specified in |
| 114 |
``obj``. Default is 'simplerepr'. Valid values are: |
| 115 |
|
| 116 |
:simplerepr: The default. This takes the ``str`` of the object and |
| 117 |
then returns the bytes version of that string. |
| 118 |
:empty: Return an empty byte string |
| 119 |
:passthru: Return the object passed in |
| 120 |
:strict: Raise a :exc:`TypeError` |
| 121 |
|
| 122 |
:returns: Typically this returns a byte string. If a nonstring object is |
| 123 |
passed in this may be a different type depending on the strategy |
| 124 |
specified by nonstring. This will never return a text string. |
| 125 |
|
| 126 |
.. note:: If passed a byte string, this function does not check that the |
| 127 |
string is valid in the specified encoding. If it's important that the |
| 128 |
byte string is in the specified encoding do:: |
| 129 |
|
| 130 |
encoded_string = to_bytes(to_text(input_string, encoding='latin-1'), encoding='utf-8') |
| 131 |
|
| 132 |
.. version_changed:: 2.3 |
| 133 |
|
| 134 |
Added the ``surrogate_then_replace`` error handler and made it the default error handler. |
| 135 |
""" |
| 136 |
if isinstance(obj, bytes): |
| 137 |
return obj |
| 138 |
|
| 139 |
# We're given a text string |
| 140 |
# If it has surrogates, we know because it will decode |
| 141 |
original_errors = errors |
| 142 |
if errors in _COMPOSED_ERROR_HANDLERS: |
| 143 |
if HAS_SURROGATEESCAPE: |
| 144 |
errors = 'surrogateescape' |
| 145 |
elif errors == 'surrogate_or_strict': |
| 146 |
errors = 'strict' |
| 147 |
else: |
| 148 |
errors = 'replace' |
| 149 |
|
| 150 |
if isinstance(obj, str): |
| 151 |
try: |
| 152 |
# Try this first as it's the fastest |
| 153 |
return obj.encode(encoding, errors) |
| 154 |
except UnicodeEncodeError: |
| 155 |
if original_errors in (None, 'surrogate_then_replace'): |
| 156 |
# We should only reach this if encoding was non-utf8 original_errors was |
| 157 |
# surrogate_then_escape and errors was surrogateescape |
| 158 |
|
| 159 |
# Slow but works |
| 160 |
return_string = obj.encode('utf-8', 'surrogateescape') |
| 161 |
return_string = return_string.decode('utf-8', 'replace') |
| 162 |
return return_string.encode(encoding, 'replace') |
| 163 |
raise |
| 164 |
|
| 165 |
# Note: We do these last even though we have to call to_bytes again on the |
| 166 |
# value because we're optimizing the common case |
| 167 |
if nonstring == 'simplerepr': |
| 168 |
try: |
| 169 |
value = str(obj) |
| 170 |
except UnicodeError: |
| 171 |
try: |
| 172 |
value = repr(obj) |
| 173 |
except UnicodeError: |
| 174 |
# Giving up |
| 175 |
return b'' |
| 176 |
elif nonstring == 'passthru': |
| 177 |
return obj |
| 178 |
elif nonstring == 'empty': |
| 179 |
return b'' |
| 180 |
elif nonstring == 'strict': |
| 181 |
raise TypeError('obj must be a string type') |
| 182 |
else: |
| 183 |
raise TypeError('Invalid value %s for to_bytes\' nonstring parameter' % nonstring) |
| 184 |
|
| 185 |
return to_bytes(value, encoding=encoding, errors=errors) |
| 186 |
|
| 187 |
|
| 188 |
@_t.overload |
| 189 |
def to_text( |
| 190 |
obj: object, |
| 191 |
encoding: str = 'utf-8', |
| 192 |
errors: str | None = None, |
| 193 |
) -> str: ... |
| 194 |
|
| 195 |
|
| 196 |
@_t.overload |
| 197 |
def to_text( |
| 198 |
obj: str | bytes, |
| 199 |
encoding: str = 'utf-8', |
| 200 |
errors: str | None = None, |
| 201 |
nonstring: _NonStringPassthru = 'passthru', |
| 202 |
) -> str: ... |
| 203 |
|
| 204 |
|
| 205 |
@_t.overload |
| 206 |
def to_text( |
| 207 |
obj: _T, |
| 208 |
encoding: str = 'utf-8', |
| 209 |
errors: str | None = None, |
| 210 |
nonstring: _NonStringPassthru = 'passthru', |
| 211 |
) -> _T: ... |
| 212 |
|
| 213 |
|
| 214 |
@_t.overload |
| 215 |
def to_text( |
| 216 |
obj: object, |
| 217 |
encoding: str = 'utf-8', |
| 218 |
errors: str | None = None, |
| 219 |
nonstring: _NonStringOther = 'simplerepr', |
| 220 |
) -> str: ... |
| 221 |
|
| 222 |
|
| 223 |
def to_text( |
| 224 |
obj: _T, |
| 225 |
encoding: str = 'utf-8', |
| 226 |
errors: str | None = None, |
| 227 |
nonstring: _NonStringAll = 'simplerepr' |
| 228 |
) -> _T | str: |
| 229 |
"""Make sure that a string is a text string |
| 230 |
|
| 231 |
:arg obj: An object to make sure is a text string. In most cases this |
| 232 |
will be either a text string or a byte string. However, with |
| 233 |
``nonstring='simplerepr'``, this can be used as a traceback-free |
| 234 |
version of ``str(obj)``. |
| 235 |
:kwarg encoding: The encoding to use to transform from a byte string to |
| 236 |
a text string. Defaults to using 'utf-8'. |
| 237 |
:kwarg errors: The error handler to use if the byte string is not |
| 238 |
decodable using the specified encoding. Any valid `codecs error |
| 239 |
handler <https://docs.python.org/3/library/codecs.html#codec-base-classes>`_ |
| 240 |
may be specified. We support three additional error strategies |
| 241 |
specifically aimed at helping people to port code: |
| 242 |
|
| 243 |
:surrogate_or_strict: Will use surrogateescape if it is a valid |
| 244 |
handler, otherwise it will use strict |
| 245 |
:surrogate_or_replace: Will use surrogateescape if it is a valid |
| 246 |
handler, otherwise it will use replace. |
| 247 |
:surrogate_then_replace: Does the same as surrogate_or_replace but |
| 248 |
`was added for symmetry with the error handlers in |
| 249 |
:func:`ansible.module_utils.common.text.converters.to_bytes` (Added in Ansible 2.3) |
| 250 |
|
| 251 |
Because surrogateescape was added in Python3 this usually means that |
| 252 |
Python3 will use `surrogateescape` and Python2 will use the fallback |
| 253 |
error handler. Note that the code checks for surrogateescape when the |
| 254 |
module is imported. If you have a backport of `surrogateescape` for |
| 255 |
python2, be sure to register the error handler prior to importing this |
| 256 |
module. |
| 257 |
|
| 258 |
The default until Ansible-2.2 was `surrogate_or_replace` |
| 259 |
In Ansible-2.3 this defaults to `surrogate_then_replace` for symmetry |
| 260 |
with :func:`ansible.module_utils.common.text.converters.to_bytes` . |
| 261 |
:kwarg nonstring: The strategy to use if a nonstring is specified in |
| 262 |
``obj``. Default is 'simplerepr'. Valid values are: |
| 263 |
|
| 264 |
:simplerepr: The default. This takes the ``str`` of the object and |
| 265 |
then returns the text version of that string. |
| 266 |
:empty: Return an empty text string |
| 267 |
:passthru: Return the object passed in |
| 268 |
:strict: Raise a :exc:`TypeError` |
| 269 |
|
| 270 |
:returns: Typically this returns a text string. If a nonstring object is |
| 271 |
passed in this may be a different type depending on the strategy |
| 272 |
specified by nonstring. This will never return a byte string. |
| 273 |
From Ansible-2.3 onwards, the default is `surrogate_then_replace`. |
| 274 |
|
| 275 |
.. version_changed:: 2.3 |
| 276 |
|
| 277 |
Added the surrogate_then_replace error handler and made it the default error handler. |
| 278 |
""" |
| 279 |
if isinstance(obj, str): |
| 280 |
return obj |
| 281 |
|
| 282 |
if errors in _COMPOSED_ERROR_HANDLERS: |
| 283 |
if HAS_SURROGATEESCAPE: |
| 284 |
errors = 'surrogateescape' |
| 285 |
elif errors == 'surrogate_or_strict': |
| 286 |
errors = 'strict' |
| 287 |
else: |
| 288 |
errors = 'replace' |
| 289 |
|
| 290 |
if isinstance(obj, bytes): |
| 291 |
# Note: We don't need special handling for surrogate_then_replace |
| 292 |
# because all bytes will either be made into surrogates or are valid |
| 293 |
# to decode. |
| 294 |
return obj.decode(encoding, errors) |
| 295 |
|
| 296 |
# Note: We do these last even though we have to call to_text again on the |
| 297 |
# value because we're optimizing the common case |
| 298 |
if nonstring == 'simplerepr': |
| 299 |
try: |
| 300 |
value = str(obj) |
| 301 |
except UnicodeError: |
| 302 |
try: |
| 303 |
value = repr(obj) |
| 304 |
except UnicodeError: |
| 305 |
# Giving up |
| 306 |
return '' |
| 307 |
elif nonstring == 'passthru': |
| 308 |
return obj |
| 309 |
elif nonstring == 'empty': |
| 310 |
return '' |
| 311 |
elif nonstring == 'strict': |
| 312 |
raise TypeError('obj must be a string type') |
| 313 |
else: |
| 314 |
raise TypeError('Invalid value %s for to_text\'s nonstring parameter' % nonstring) |
| 315 |
|
| 316 |
return to_text(value, encoding=encoding, errors=errors) |
| 317 |
|
| 318 |
|
| 319 |
to_native = to_text |
| 320 |
|
| 321 |
|
| 322 |
def jsonify(data, **kwargs): |
| 323 |
from ansible.module_utils.common import json as _common_json |
| 324 |
# from ansible.module_utils.common.warnings import deprecate |
| 325 |
|
| 326 |
# deprecated: description='deprecate jsonify()' core_version='2.23' |
| 327 |
# deprecate( |
| 328 |
# msg="The `jsonify` function is deprecated.", |
| 329 |
# version="2.27", |
| 330 |
# # help_text="", # DTFIX-FUTURE: fill in this help text |
| 331 |
# ) |
| 332 |
|
| 333 |
return json.dumps(data, cls=_common_json._get_legacy_encoder(), _decode_bytes=True, **kwargs) |
| 334 |
|
| 335 |
|
| 336 |
def container_to_bytes(d, encoding='utf-8', errors='surrogate_or_strict'): |
| 337 |
""" Recursively convert dict keys and values to byte str |
| 338 |
|
| 339 |
Specialized for json return because this only handles, lists, tuples, |
| 340 |
and dict container types (the containers that the json module returns) |
| 341 |
""" |
| 342 |
# DTFIX-FUTURE: deprecate |
| 343 |
|
| 344 |
if isinstance(d, str): |
| 345 |
return to_bytes(d, encoding=encoding, errors=errors) |
| 346 |
elif isinstance(d, dict): |
| 347 |
return dict(container_to_bytes(o, encoding, errors) for o in d.items()) |
| 348 |
elif isinstance(d, list): |
| 349 |
return [container_to_bytes(o, encoding, errors) for o in d] |
| 350 |
elif isinstance(d, tuple): |
| 351 |
return tuple(container_to_bytes(o, encoding, errors) for o in d) |
| 352 |
else: |
| 353 |
return d |
| 354 |
|
| 355 |
|
| 356 |
def container_to_text(d, encoding='utf-8', errors='surrogate_or_strict'): |
| 357 |
"""Recursively convert dict keys and values to text str |
| 358 |
|
| 359 |
Specialized for json return because this only handles, lists, tuples, |
| 360 |
and dict container types (the containers that the json module returns) |
| 361 |
""" |
| 362 |
# DTFIX-FUTURE: deprecate |
| 363 |
|
| 364 |
if isinstance(d, bytes): |
| 365 |
# Warning, can traceback |
| 366 |
return to_text(d, encoding=encoding, errors=errors) |
| 367 |
elif isinstance(d, dict): |
| 368 |
return dict(container_to_text(o, encoding, errors) for o in d.items()) |
| 369 |
elif isinstance(d, list): |
| 370 |
return [container_to_text(o, encoding, errors) for o in d] |
| 371 |
elif isinstance(d, tuple): |
| 372 |
return tuple(container_to_text(o, encoding, errors) for o in d) |
| 373 |
else: |
| 374 |
return d |
| 375 |
|
| 376 |
|
| 377 |
def __getattr__(importable_name): |
| 378 |
return _no_six.deprecate(importable_name, __name__, "binary_type", "text_type", "iteritems") |