changeset 51749:16d63d7799fa

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.
author Mads Kiilerich <mads@kiilerich.com>
date Mon, 22 Jul 2024 18:20:03 +0200
parents 3149dc824a94
children c87c56ad6913
files mercurial/utils/resourceutil.py
diffstat 1 files changed, 20 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- 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)