# HG changeset patch # User RhodeCode Admin # Date 2023-06-06 08:50:55 # Node ID 24c9b8ea07189dccf04b6a0fde0829920df4bc60 # Parent 879da4f318b692ff5768ebdbb0a46ba4eb1de600 utils: added few typing fixes to str_utils diff --git a/vcsserver/str_utils.py b/vcsserver/str_utils.py --- a/vcsserver/str_utils.py +++ b/vcsserver/str_utils.py @@ -15,6 +15,8 @@ # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +import typing +import base64 import logging @@ -38,14 +40,20 @@ def safe_int(val, default=None) -> int: return val +def base64_to_str(text) -> str: + return safe_str(base64.encodebytes(safe_bytes(text))).strip() + + +def get_default_encodings() -> typing.List[str]: + return ['utf8'] + + def safe_str(str_, to_encoding=None) -> str: """ safe str function. Does few trick to turn unicode_ into string :param str_: str to encode :param to_encoding: encode to this type UTF8 default - :rtype: str - :returns: str object """ if isinstance(str_, str): return str_ @@ -54,7 +62,7 @@ def safe_str(str_, to_encoding=None) -> if not isinstance(str_, bytes): return str(str_) - to_encoding = to_encoding or ['utf8'] + to_encoding = to_encoding or get_default_encodings() if not isinstance(to_encoding, (list, tuple)): to_encoding = [to_encoding] @@ -73,16 +81,14 @@ def safe_bytes(str_, from_encoding=None) :param str_: string to decode :param from_encoding: encode from this type UTF8 default - :rtype: unicode - :returns: unicode object """ if isinstance(str_, bytes): return str_ if not isinstance(str_, str): - raise ValueError('safe_bytes cannot convert other types than str: got: {}'.format(type(str_))) + raise ValueError(f'safe_bytes cannot convert other types than str: got: {type(str_)}') - from_encoding = from_encoding or ['utf8'] + from_encoding = from_encoding or get_default_encodings() if not isinstance(from_encoding, (list, tuple)): from_encoding = [from_encoding] @@ -108,11 +114,11 @@ def ascii_bytes(str_, allow_bytes=False) return str_ if not isinstance(str_, str): - raise ValueError('ascii_bytes cannot convert other types than str: got: {}'.format(type(str_))) + raise ValueError(f'ascii_bytes cannot convert other types than str: got: {type(str_)}') return str_.encode('ascii') -def ascii_str(str_): +def ascii_str(str_) -> str: """ Simple conversion from bytes to str, with assumption that str_ is pure ASCII. Fails with UnicodeError on invalid input. @@ -123,5 +129,5 @@ def ascii_str(str_): """ if not isinstance(str_, bytes): - raise ValueError('ascii_str cannot convert other types than bytes: got: {}'.format(type(str_))) + raise ValueError(f'ascii_str cannot convert other types than bytes: got: {type(str_)}') return str_.decode('ascii')