| |
| |
| """Common compatibility code.""" |
| |
| |
| |
| |
| |
|
|
| import builtins |
| import sys |
|
|
| on_win = bool(sys.platform == "win32") |
| on_mac = bool(sys.platform == "darwin") |
| on_linux = bool(sys.platform == "linux") |
|
|
| |
| ENCODE_ENVIRONMENT = True |
|
|
|
|
| def encode_for_env_var(value) -> str: |
| """Environment names and values need to be string.""" |
| if isinstance(value, str): |
| return value |
| elif isinstance(value, bytes): |
| return value.decode() |
| return str(value) |
|
|
|
|
| def encode_environment(env): |
| if ENCODE_ENVIRONMENT: |
| env = {encode_for_env_var(k): encode_for_env_var(v) for k, v in env.items()} |
| return env |
|
|
|
|
| from collections.abc import Iterable |
|
|
|
|
| def isiterable(obj): |
| return not isinstance(obj, str) and isinstance(obj, Iterable) |
|
|
|
|
| |
| |
| |
|
|
| from collections import OrderedDict as odict |
|
|
|
|
| def open_utf8( |
| file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True |
| ): |
| if "b" in mode: |
| return builtins.open( |
| file, |
| str(mode), |
| buffering=buffering, |
| errors=errors, |
| newline=newline, |
| closefd=closefd, |
| ) |
| else: |
| return builtins.open( |
| file, |
| str(mode), |
| buffering=buffering, |
| encoding=encoding or "utf-8", |
| errors=errors, |
| newline=newline, |
| closefd=closefd, |
| ) |
|
|
|
|
| NoneType = type(None) |
| primitive_types = (str, int, float, complex, bool, NoneType) |
|
|
|
|
| def ensure_binary(value): |
| try: |
| return value.encode("utf-8") |
| except AttributeError: |
| |
| |
| return value |
|
|
|
|
| def ensure_text_type(value) -> str: |
| try: |
| return value.decode("utf-8") |
| except AttributeError: |
| |
| |
| return value |
| except UnicodeDecodeError: |
| from charset_normalizer import from_bytes |
|
|
| return str(from_bytes(value).best()) |
| except UnicodeEncodeError: |
| |
| |
| |
| return value |
|
|
|
|
| def ensure_utf8_encoding(value): |
| try: |
| return value.encode("utf-8") |
| except AttributeError: |
| return value |
| except UnicodeEncodeError: |
| return value |
|
|