Mercurial > hgrepos > Python > apps > py-cutils
diff 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 |
line wrap: on
line diff
--- a/cutils/util/__init__.py Fri Jan 10 11:38:31 2025 +0100 +++ b/cutils/util/__init__.py Fri Jan 10 12:46:44 2025 +0100 @@ -8,6 +8,7 @@ """ __all__ = ["PY2", + "PY35", "normalize_filename", "argv2algo", "algotag2algotype", @@ -26,6 +27,7 @@ PY2 = sys.version_info[0] < 3 +PY35 = sys.version_info[:2] >= (3, 5) def default_algotag(): @@ -191,3 +193,33 @@ if isinstance(what, bytes): return what return os.fsencode(what) + + +def interpolate_bytes(formatstr, *values): + """Interpolate byte strings also on Python 3.4. + + :param bytes formatstr: + :param values: params for interpolation: may *not* contain Unicode strings + :rvalue: the formatted octet + :rtype: bytes + + """ + assert isinstance(formatstr, bytes) + # Python 3.5+ or Python2 know how to interpolate byte strings + if PY35 or PY2: + return formatstr % values + # Workaround with a Latin-1 dance + tformatstr = formatstr.decode("latin1") + tvalues = [] + for v in values: + if PY2: + if isinstance(v, unicode): # noqa: F821 undefined name 'unicode' + assert False + else: + if isinstance(v, str): + assert False + if isinstance(v, bytes): + tvalues.append(v.decode("latin1")) + else: + tvalues.append(v) + return (tformatstr % tuple(tvalues)).encode("latin1")
