1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-03-21 20:59:10 +00:00

python_requirements_info: use importlib.metadata when available (#11495)

Use importlib.metadata when available.
This commit is contained in:
Felix Fontein 2026-02-10 22:44:06 +01:00 committed by GitHub
parent 63ddca7f21
commit 88adca3fb4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 34 additions and 12 deletions

View file

@ -158,6 +158,8 @@ ignore_missing_imports = True
ignore_missing_imports = True
[mypy-pingdom.*]
ignore_missing_imports = True
[mypy-pkg_resources.*]
ignore_missing_imports = True
[mypy-portage.*]
ignore_missing_imports = True
[mypy-potatoes_that_will_never_be_there.*]

View file

@ -0,0 +1,4 @@
bugfixes:
- "python_requirements_info - use ``importlib.metadata`` if ``pkg_resources`` from ``setuptools`` cannot be imported.
That module has been removed from setuptools 82.0.0
(https://github.com/ansible-collections/community.general/issues/11491, https://github.com/ansible-collections/community.general/pull/11492)."

View file

@ -121,18 +121,26 @@ import operator
import re
import sys
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.version import LooseVersion
HAS_IMPORTLIB_METADATA = False
try:
import importlib.metadata
HAS_IMPORTLIB_METADATA = True
except ImportError:
pass
HAS_DISTUTILS = False
try:
import pkg_resources
from ansible_collections.community.general.plugins.module_utils.version import LooseVersion
HAS_DISTUTILS = True
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
operations = {
"<=": operator.le,
">=": operator.ge,
@ -155,9 +163,9 @@ def main():
argument_spec=dict(dependencies=dict(type="list", elements="str", default=[])),
supports_check_mode=True,
)
if not HAS_DISTUTILS:
if not HAS_DISTUTILS and not HAS_IMPORTLIB_METADATA:
module.fail_json(
msg='Could not import "distutils" and "pkg_resources" libraries to introspect python environment.',
msg='Could not import "pkg_resources" or "importlib.metadata" libraries to introspect Python environment.',
python=sys.executable,
python_version=sys.version,
python_version_info=python_version_info,
@ -180,12 +188,20 @@ def main():
module.fail_json(
msg=f"Failed to parse version requirement '{dep}'. Operator must be one of >, <, <=, >=, or =="
)
try:
existing = pkg_resources.get_distribution(pkg).version
except pkg_resources.DistributionNotFound:
# not there
results["not_found"].append(pkg)
continue
if HAS_DISTUTILS:
try:
existing = pkg_resources.get_distribution(pkg).version
except pkg_resources.DistributionNotFound:
# not there
results["not_found"].append(pkg)
continue
else:
try:
existing = importlib.metadata.version(pkg)
except importlib.metadata.PackageNotFoundError:
# not there
results["not_found"].append(pkg)
continue
if op is None and version is None:
results["valid"][pkg] = {
"installed": existing,