Mercurial > hg
diff mercurial/utils/resourceutil.py @ 51669:32a1c9226dd9
typing: add type hints to `mercurial/utils/resourceutil.py`
The `except` path requires byte args (because of the byte based manipulation in
`_package_path()`), while the `else` case tolerates `AnyStr`. Pytype was unable
to figure this out, and we should make sure the interface is the same for all
environments.
author | Matt Harbison <matt_harbison@yahoo.com> |
---|---|
date | Wed, 10 Jul 2024 15:49:16 -0400 |
parents | d718eddf01d9 |
children | 493034cc3265 |
line wrap: on
line diff
--- a/mercurial/utils/resourceutil.py Mon Jul 08 17:56:54 2024 +0200 +++ b/mercurial/utils/resourceutil.py Wed Jul 10 15:49:16 2024 -0400 @@ -11,10 +11,18 @@ import _imp import os import sys +import typing from .. import pycompat +if typing.TYPE_CHECKING: + from typing import ( + BinaryIO, + Iterator, + ) + + def mainfrozen(): """return True if we are a frozen executable. @@ -39,7 +47,7 @@ # leading "mercurial." off of the package name, so that these # pseudo resources are found in their directory next to the # executable. - def _package_path(package): + def _package_path(package: bytes) -> bytes: dirs = package.split(b".") assert dirs[0] == b"mercurial" return os.path.join(_rootpath, *dirs[1:]) @@ -49,7 +57,7 @@ datapath = os.path.dirname(os.path.dirname(pycompat.fsencode(__file__))) _rootpath = os.path.dirname(datapath) - def _package_path(package): + def _package_path(package: bytes) -> bytes: return os.path.join(_rootpath, *package.split(b".")) @@ -72,11 +80,11 @@ # importlib.resources was not found (almost definitely because we're on a # Python version before 3.7) - def open_resource(package, name): + def open_resource(package: bytes, name: bytes) -> "BinaryIO": path = os.path.join(_package_path(package), name) return open(path, "rb") - def is_resource(package, name): + def is_resource(package: bytes, name: bytes) -> bool: path = os.path.join(_package_path(package), name) try: @@ -84,7 +92,7 @@ except (IOError, OSError): return False - def contents(package): + def contents(package: bytes) -> "Iterator[bytes]": path = pycompat.fsdecode(_package_path(package)) for p in os.listdir(path): @@ -94,7 +102,7 @@ else: from .. import encoding - def open_resource(package, name): + def open_resource(package: bytes, name: bytes) -> "BinaryIO": if hasattr(resources, 'files'): return ( resources.files( # pytype: disable=module-attr @@ -108,12 +116,12 @@ pycompat.sysstr(package), pycompat.sysstr(name) ) - def is_resource(package, name): + def is_resource(package: bytes, name: bytes) -> bool: return resources.is_resource( # pytype: disable=module-attr pycompat.sysstr(package), encoding.strfromlocal(name) ) - def contents(package): + def contents(package: bytes) -> "Iterator[bytes]": # pytype: disable=module-attr for r in resources.contents(pycompat.sysstr(package)): # pytype: enable=module-attr