codekingpro/portable-devtools
115k
1# This file is dual licensed under the terms of the Apache License, Version2# 2.0, and the BSD License. See the LICENSE file in the root of this repository3# for complete details.4 5from __future__ import annotations6 7import enum8import sys9import types10import typing11import warnings12from collections.abc import Callable, Sequence13 14 15# We use a UserWarning subclass, instead of DeprecationWarning, because CPython16# decided deprecation warnings should be invisible by default.17class CryptographyDeprecationWarning(UserWarning):18 pass19 20 21# Several APIs were deprecated with no specific end-of-life date because of the22# ubiquity of their use. They should not be removed until we agree on when that23# cycle ends.24DeprecatedIn36 = CryptographyDeprecationWarning25DeprecatedIn40 = CryptographyDeprecationWarning26DeprecatedIn41 = CryptographyDeprecationWarning27DeprecatedIn42 = CryptographyDeprecationWarning28DeprecatedIn43 = CryptographyDeprecationWarning29DeprecatedIn47 = CryptographyDeprecationWarning30 31 32# If you're wondering why we don't use `Buffer`, it's because `Buffer` would33# be more accurately named: Bufferable. It means something which has an34# `__buffer__`. Which means you can't actually treat the result as a buffer35# (and do things like take a `len()`).36Buffer = typing.Union[bytes, bytearray, memoryview]37 38 39def _check_bytes(name: str, value: bytes) -> None:40 if not isinstance(value, bytes):41 raise TypeError(f"{name} must be bytes")42 43 44def _check_byteslike(name: str, value: Buffer) -> None:45 try:46 memoryview(value)47 except TypeError:48 raise TypeError(f"{name} must be bytes-like")49 50 51def int_to_bytes(integer: int, length: int | None = None) -> bytes:52 if length == 0:53 raise ValueError("length argument can't be 0")54 return integer.to_bytes(55 length or (integer.bit_length() + 7) // 8 or 1, "big"56 )57 58 59class InterfaceNotImplemented(Exception):60 pass61 62 63class _DeprecatedValue:64 def __init__(self, value: object, message: str, warning_class):65 self.value = value66 self.message = message67 self.warning_class = warning_class68 69 70class _ModuleWithDeprecations(types.ModuleType):71 def __init__(self, module: types.ModuleType):72 super().__init__(module.__name__)73 self.__dict__["_module"] = module74 75 def __getattr__(self, name: str) -> typing.Any:76 obj = getattr(self._module, name)77 if isinstance(obj, _DeprecatedValue):78 warnings.warn(obj.message, obj.warning_class, stacklevel=2)79 obj = obj.value80 return obj81 82 def __setattr__(self, attr: str, value: object) -> None:83 setattr(self._module, attr, value)84 85 def __delattr__(self, attr: str) -> None:86 obj = getattr(self._module, attr)87 if isinstance(obj, _DeprecatedValue):88 warnings.warn(obj.message, obj.warning_class, stacklevel=2)89 90 delattr(self._module, attr)91 92 def __dir__(self) -> Sequence[str]:93 return ["_module", *dir(self._module)]94 95 96def deprecated(97 value: object,98 module_name: str,99 message: str,100 warning_class: type[Warning],101 name: str | None = None,102) -> _DeprecatedValue:103 module = sys.modules[module_name]104 if not isinstance(module, _ModuleWithDeprecations):105 sys.modules[module_name] = module = _ModuleWithDeprecations(module)106 dv = _DeprecatedValue(value, message, warning_class)107 # Maintain backwards compatibility with `name is None` for pyOpenSSL.108 if name is not None:109 setattr(module, name, dv)110 return dv111 112 113def cached_property(func: Callable) -> property:114 cached_name = f"_cached_{func}"115 sentinel = object()116 117 def inner(instance: object):118 cache = getattr(instance, cached_name, sentinel)119 if cache is not sentinel:120 return cache121 result = func(instance)122 setattr(instance, cached_name, result)123 return result124 125 return property(inner)126 127 128# Python 3.10 changed representation of enums. We use well-defined object129# representation and string representation from Python 3.9.130class Enum(enum.Enum):131 def __repr__(self) -> str:132 return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>"133 134 def __str__(self) -> str:135 return f"{self.__class__.__name__}.{self._name_}"136 