Mercurial > hgrepos > Python > apps > py-cutils
comparison cutils/util/__init__.py @ 173:e081b6ee5570
treesum.py now runs on Python3.4 also: use a workaround for its missing byte % formatting.
No extra module is required for it to run using sha SHA and SHA-2 family of
digests.
| author | Franz Glasner <fzglas.hg@dom66.de> |
|---|---|
| date | Fri, 10 Jan 2025 12:46:44 +0100 |
| parents | 804a823c63f5 |
| children | 6154b8e4ba94 |
comparison
equal
deleted
inserted
replaced
| 172:804a823c63f5 | 173:e081b6ee5570 |
|---|---|
| 6 r"""Utility package. | 6 r"""Utility package. |
| 7 | 7 |
| 8 """ | 8 """ |
| 9 | 9 |
| 10 __all__ = ["PY2", | 10 __all__ = ["PY2", |
| 11 "PY35", | |
| 11 "normalize_filename", | 12 "normalize_filename", |
| 12 "argv2algo", | 13 "argv2algo", |
| 13 "algotag2algotype", | 14 "algotag2algotype", |
| 14 "get_blake2b", | 15 "get_blake2b", |
| 15 "get_blake2b_256", | 16 "get_blake2b_256", |
| 24 import os | 25 import os |
| 25 import sys | 26 import sys |
| 26 | 27 |
| 27 | 28 |
| 28 PY2 = sys.version_info[0] < 3 | 29 PY2 = sys.version_info[0] < 3 |
| 30 PY35 = sys.version_info[:2] >= (3, 5) | |
| 29 | 31 |
| 30 | 32 |
| 31 def default_algotag(): | 33 def default_algotag(): |
| 32 """Determine the "best" default algorithm. | 34 """Determine the "best" default algorithm. |
| 33 | 35 |
| 189 | 191 |
| 190 """ | 192 """ |
| 191 if isinstance(what, bytes): | 193 if isinstance(what, bytes): |
| 192 return what | 194 return what |
| 193 return os.fsencode(what) | 195 return os.fsencode(what) |
| 196 | |
| 197 | |
| 198 def interpolate_bytes(formatstr, *values): | |
| 199 """Interpolate byte strings also on Python 3.4. | |
| 200 | |
| 201 :param bytes formatstr: | |
| 202 :param values: params for interpolation: may *not* contain Unicode strings | |
| 203 :rvalue: the formatted octet | |
| 204 :rtype: bytes | |
| 205 | |
| 206 """ | |
| 207 assert isinstance(formatstr, bytes) | |
| 208 # Python 3.5+ or Python2 know how to interpolate byte strings | |
| 209 if PY35 or PY2: | |
| 210 return formatstr % values | |
| 211 # Workaround with a Latin-1 dance | |
| 212 tformatstr = formatstr.decode("latin1") | |
| 213 tvalues = [] | |
| 214 for v in values: | |
| 215 if PY2: | |
| 216 if isinstance(v, unicode): # noqa: F821 undefined name 'unicode' | |
| 217 assert False | |
| 218 else: | |
| 219 if isinstance(v, str): | |
| 220 assert False | |
| 221 if isinstance(v, bytes): | |
| 222 tvalues.append(v.decode("latin1")) | |
| 223 else: | |
| 224 tvalues.append(v) | |
| 225 return (tformatstr % tuple(tvalues)).encode("latin1") |
