utils: fix resourceutil use of deprecated importlib.resources
authorMads Kiilerich <mads@kiilerich.com>
Mon, 22 Jul 2024 18:20:03 +0200
changeset 51749 16d63d7799fa
parent 51748 3149dc824a94
child 51750 c87c56ad6913
utils: fix resourceutil use of deprecated importlib.resources Some importlib functionality was deprecated in 3.11 . The documentation on https://docs.python.org/3.12/library/importlib.resources.html recommends using the new .files() API that was introduced in 3.9.
mercurial/utils/resourceutil.py
--- a/mercurial/utils/resourceutil.py	Thu Jan 11 20:32:07 2024 +0100
+++ b/mercurial/utils/resourceutil.py	Mon Jul 22 18:20:03 2024 +0200
@@ -66,7 +66,7 @@
     from importlib import resources  # pytype: disable=import-error
 
     # Force loading of the resources module
-    if hasattr(resources, 'files'):
+    if hasattr(resources, 'files'):  # Introduced in Python 3.9
         resources.files  # pytype: disable=module-attr
     else:
         resources.open_binary  # pytype: disable=module-attr
@@ -115,12 +115,24 @@
             )
 
     def is_resource(package: bytes, name: bytes) -> bool:
-        return resources.is_resource(  # pytype: disable=module-attr
-            pycompat.sysstr(package), encoding.strfromlocal(name)
-        )
+        if hasattr(resources, 'files'):  # Introduced in Python 3.9
+            return (
+                resources.files(pycompat.sysstr(package))
+                .joinpath(encoding.strfromlocal(name))
+                .is_file()
+            )
+        else:
+            return resources.is_resource(  # pytype: disable=module-attr
+                pycompat.sysstr(package), encoding.strfromlocal(name)
+            )
 
     def contents(package: bytes) -> "Iterator[bytes]":
-        # pytype: disable=module-attr
-        for r in resources.contents(pycompat.sysstr(package)):
-            # pytype: enable=module-attr
-            yield encoding.strtolocal(r)
+        if hasattr(resources, 'files'):  # Introduced in Python 3.9
+            for path in resources.files(pycompat.sysstr(package)).iterdir():
+                if path.is_file():
+                    yield encoding.strtolocal(path.name)
+        else:
+            # pytype: disable=module-attr
+            for r in resources.contents(pycompat.sysstr(package)):
+                # pytype: enable=module-attr
+                yield encoding.strtolocal(r)