Debian Codegraph @

lib/ansible/galaxy/dependency_resolution/dataclasses.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright: (c) 2020-2021, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 """Dependency structs."""
5 # FIXME: add caching all over the place
6
7 from __future__ import annotations
8
9 import collections.abc as _c
10 import os
11 import pathlib
12 import typing as t
13
14 from collections import namedtuple
15 from glob import iglob
16 from urllib.parse import urlparse
17 from yaml import safe_load
18
19 if t.TYPE_CHECKING:
20 from ansible.galaxy.collection.concrete_artifact_manager import (
21 ConcreteArtifactsManager,
22 )
23 Collection = t.TypeVar(
24 'Collection',
25 'Candidate', 'Requirement',
26 '_ComputedReqKindsMixin',
27 )
28
29 from ansible import constants as C
30 from ansible.errors import AnsibleError, AnsibleAssertionError
31 from ansible.galaxy.api import GalaxyAPI
32 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
33 from ansible.module_utils.common.arg_spec import ArgumentSpecValidator
34 from ansible.plugins.loader import _does_collection_support_ansible_version
35 from ansible.release import __version__
36 from ansible.utils.collection_loader import AnsibleCollectionRef
37 from ansible.utils.display import Display
38
39 from .. import collection as _glx_coll_mod
40
41
42 _ALLOW_CONCRETE_POINTER_IN_SOURCE = False # NOTE: This is a feature flag
43 _GALAXY_YAML = b'galaxy.yml'
44 _MANIFEST_JSON = b'MANIFEST.json'
45 _SOURCE_METADATA_FILE = b'GALAXY.yml'
46
47 display = Display()
48
49
50 def get_validated_source_info(
51 b_source_info_path: bytes,
52 namespace: str,
53 name: str,
54 version: str,
55 ) -> dict[str, object] | None:
56 source_info_path = to_text(b_source_info_path, errors='surrogate_or_strict')
57
58 if not os.path.isfile(b_source_info_path):
59 return None
60
61 try:
62 with open(b_source_info_path, mode='rb') as fd:
63 metadata = safe_load(fd)
64 except OSError as e:
65 display.warning(
66 f"Error getting collection source information at '{source_info_path}': {to_text(e, errors='surrogate_or_strict')}"
67 )
68 return None
69
70 if not isinstance(metadata, dict):
71 display.warning(f"Error getting collection source information at '{source_info_path}': expected a YAML dictionary")
72 return None
73
74 schema_errors = _validate_v1_source_info_schema(namespace, name, version, metadata)
75 if schema_errors:
76 display.warning(f"Ignoring source metadata file at {source_info_path} due to the following errors:")
77 display.warning("\n".join(schema_errors))
78 display.warning("Correct the source metadata file by reinstalling the collection.")
79 return None
80
81 return metadata
82
83
84 def _validate_v1_source_info_schema(
85 namespace: str,
86 name: str,
87 version: str,
88 provided_arguments: dict[str, object],
89 ) -> list[str]:
90 argument_spec_data = dict(
91 format_version=dict(choices=["1.0.0"]),
92 download_url=dict(),
93 version_url=dict(),
94 server=dict(),
95 signatures=dict(
96 type="list",
97 elements="dict",
98 options=dict(
99 signature=dict(),
100 pubkey_fingerprint=dict(),
101 signing_service=dict(),
102 pulp_created=dict(),
103 )
104 ),
105 name=dict(choices=[name]),
106 namespace=dict(choices=[namespace]),
107 version=dict(choices=[version]),
108 )
109
110 if not isinstance(provided_arguments, dict):
111 raise AnsibleError(
112 f'Invalid offline source info for {namespace}.{name}:{version}, expected a dict and got {type(provided_arguments)}'
113 )
114 validator = ArgumentSpecValidator(argument_spec_data)
115 validation_result = validator.validate(provided_arguments)
116
117 return validation_result.error_messages
118
119
120 def _is_collection_src_dir(dir_path: bytes | str) -> bool:
121 b_dir_path = to_bytes(dir_path, errors='surrogate_or_strict')
122 return os.path.isfile(os.path.join(b_dir_path, _GALAXY_YAML))
123
124
125 def _is_installed_collection_dir(dir_path: bytes | str) -> bool:
126 b_dir_path = to_bytes(dir_path, errors='surrogate_or_strict')
127 return os.path.isfile(os.path.join(b_dir_path, _MANIFEST_JSON))
128
129
130 def _is_collection_dir(dir_path: bytes | str) -> bool:
131 return (
132 _is_installed_collection_dir(dir_path) or
133 _is_collection_src_dir(dir_path)
134 )
135
136
137 def _find_collections_in_subdirs(dir_path: str) -> _c.Iterator[bytes]:
138 b_dir_path = to_bytes(dir_path, errors='surrogate_or_strict')
139
140 subdir_glob_pattern = os.path.join(
141 b_dir_path,
142 # b'*', # namespace is supposed to be top-level per spec
143 b'*', # collection name
144 )
145
146 for subdir in iglob(subdir_glob_pattern):
147 if os.path.isfile(os.path.join(subdir, _MANIFEST_JSON)):
148 yield subdir
149 elif os.path.isfile(os.path.join(subdir, _GALAXY_YAML)):
150 yield subdir
151
152
153 def _is_collection_namespace_dir(tested_str: str) -> bool:
154 return any(_find_collections_in_subdirs(tested_str))
155
156
157 def _is_file_path(tested_str: str) -> bool:
158 return os.path.isfile(to_bytes(tested_str, errors='surrogate_or_strict'))
159
160
161 def _is_http_url(tested_str: str) -> bool:
162 return urlparse(tested_str).scheme.lower() in {'http', 'https'}
163
164
165 def _is_git_url(tested_str: str) -> bool:
166 return tested_str.startswith(('git+', 'git@'))
167
168
169 def _is_concrete_artifact_pointer(tested_str: str) -> bool:
170 return any(
171 predicate(tested_str)
172 for predicate in (
173 # NOTE: Maintain the checks to be sorted from light to heavy:
174 _is_git_url,
175 _is_http_url,
176 _is_file_path,
177 _is_collection_dir,
178 _is_collection_namespace_dir,
179 )
180 )
181
182
183 class _ComputedReqKindsMixin:
184 UNIQUE_ATTRS = ('fqcn', 'ver', 'src', 'type')
185
186 def __init__(self, *args, **kwargs) -> None:
187 if not self.may_have_offline_galaxy_info:
188 self._source_info = None
189 else:
190 info_path = self.construct_galaxy_info_path(to_bytes(self.src, errors='surrogate_or_strict'))
191
192 self._source_info = get_validated_source_info(
193 info_path,
194 self.namespace,
195 self.name,
196 self.ver
197 )
198
199 def __hash__(self) -> int:
200 return hash(tuple(getattr(self, attr) for attr in _ComputedReqKindsMixin.UNIQUE_ATTRS))
201
202 def __eq__(self, candidate: _c.Hashable) -> bool:
203 return hash(self) == hash(candidate)
204
205 @classmethod
206 def from_dir_path_as_unknown(
207 cls,
208 dir_path: bytes,
209 art_mgr: ConcreteArtifactsManager,
210 ) -> t.Self:
211 """Make collection from an unspecified dir type.
212
213 This alternative constructor attempts to grab metadata from the
214 given path if it's a directory. If there's no metadata, it
215 falls back to guessing the FQCN based on the directory path and
216 sets the version to "*".
217
218 It raises a ValueError immediately if the input is not an
219 existing directory path.
220 """
221 if not os.path.isdir(dir_path):
222 raise ValueError(
223 "The collection directory '{path!s}' doesn't exist".
224 format(path=to_native(dir_path)),
225 )
226
227 try:
228 return cls.from_dir_path(dir_path, art_mgr)
229 except ValueError:
230 return cls.from_dir_path_implicit(dir_path)
231
232 @classmethod
233 def from_dir_path(
234 cls,
235 dir_path: bytes,
236 art_mgr: ConcreteArtifactsManager,
237 ) -> t.Self:
238 """Make collection from an directory with metadata."""
239 if dir_path.endswith(to_bytes(os.path.sep)):
240 dir_path = dir_path.rstrip(to_bytes(os.path.sep))
241 if not _is_collection_dir(dir_path):
242 dir_pathlib = pathlib.Path(to_text(dir_path))
243 display.warning(
244 u"Collection at '{path!s}' does not have a {manifest_json!s} "
245 u'file, nor has it {galaxy_yml!s}: cannot detect version.'.
246 format(
247 galaxy_yml=to_text(_GALAXY_YAML),
248 manifest_json=to_text(_MANIFEST_JSON),
249 path=to_text(dir_path, errors='surrogate_or_strict'),
250 ),
251 )
252 raise ValueError(
253 '`dir_path` argument must be an installed or a source'
254 ' collection directory.',
255 )
256
257 tmp_inst_req = cls(None, None, dir_path, 'dir', None)
258 req_version = art_mgr.get_direct_collection_version(tmp_inst_req)
259 try:
260 req_name = art_mgr.get_direct_collection_fqcn(tmp_inst_req)
261 except TypeError as err:
262 # Looks like installed/source dir but isn't: doesn't have valid metadata.
263 display.warning(
264 u"Collection at '{path!s}' has a {manifest_json!s} "
265 u"or {galaxy_yml!s} file but it contains invalid metadata.".
266 format(
267 galaxy_yml=to_text(_GALAXY_YAML),
268 manifest_json=to_text(_MANIFEST_JSON),
269 path=to_text(dir_path, errors='surrogate_or_strict'),
270 ),
271 )
272 raise ValueError(
273 "Collection at '{path!s}' has invalid metadata".
274 format(path=to_text(dir_path, errors='surrogate_or_strict'))
275 ) from err
276
277 return cls(req_name, req_version, dir_path, 'dir', None)
278
279 @classmethod
280 def from_dir_path_implicit(
281 cls,
282 dir_path: bytes,
283 ) -> t.Self:
284 """Construct a collection instance based on an arbitrary dir.
285
286 This alternative constructor infers the FQCN based on the parent
287 and current directory names. It also sets the version to "*"
288 regardless of whether any of known metadata files are present.
289 """
290 # There is no metadata, but it isn't required for a functional collection. Determine the namespace.name from the path.
291 if dir_path.endswith(to_bytes(os.path.sep)):
292 dir_path = dir_path.rstrip(to_bytes(os.path.sep))
293 u_dir_path = to_text(dir_path, errors='surrogate_or_strict')
294 path_list = u_dir_path.split(os.path.sep)
295 req_name = '.'.join(path_list[-2:])
296 return cls(req_name, '*', dir_path, 'dir', None)
297
298 @classmethod
299 def from_string(
300 cls,
301 collection_input: str,
302 artifacts_manager: ConcreteArtifactsManager,
303 supplemental_signatures: list[str] | None,
304 ) -> t.Self:
305 req: dict[str, str | list[str] | None] = {}
306 if _is_concrete_artifact_pointer(collection_input) or AnsibleCollectionRef.is_valid_collection_name(collection_input):
307 # Arg is a file path or URL to a collection, or just a collection
308 req['name'] = collection_input
309 elif ':' in collection_input:
310 req['name'], _sep, req['version'] = collection_input.partition(':')
311 if not req['version']:
312 del req['version']
313 else:
314 if not _glx_coll_mod.HAS_PACKAGING:
315 raise AnsibleError("Failed to import packaging, check that a supported version is installed")
316 try:
317 pkg_req = _glx_coll_mod.PkgReq(collection_input)
318 except Exception as e:
319 # packaging doesn't know what this is, let it fly, better errors happen in from_requirement_dict
320 req['name'] = collection_input
321 else:
322 req['name'] = pkg_req.name
323 if pkg_req.specifier:
324 req['version'] = to_text(pkg_req.specifier)
325 req['signatures'] = supplemental_signatures
326
327 return cls.from_requirement_dict(req, artifacts_manager)
328
329 @classmethod
330 def from_requirement_dict(
331 cls,
332 # NOTE: The actual `collection_req` shape is supposed to be
333 # NOTE: `dict[str, str | list[str] | None]`
334 collection_req: dict[str, t.Any],
335 art_mgr: ConcreteArtifactsManager,
336 validate_signature_options: bool = True,
337 ) -> t.Self:
338 req_name = collection_req.get('name', None)
339 req_version = collection_req.get('version', '*')
340 req_type = collection_req.get('type')
341 # TODO: decide how to deprecate the old src API behavior
342 req_source = collection_req.get('source', None)
343 req_signature_sources = collection_req.get('signatures', None)
344 if req_signature_sources is not None:
345 if validate_signature_options and art_mgr.keyring is None:
346 raise AnsibleError(
347 f"Signatures were provided to verify {req_name} but no keyring was configured."
348 )
349
350 if not isinstance(req_signature_sources, _c.MutableSequence):
351 req_signature_sources = [req_signature_sources]
352 req_signature_sources = frozenset(req_signature_sources)
353
354 if req_type is None:
355 if ( # FIXME: decide on the future behavior:
356 _ALLOW_CONCRETE_POINTER_IN_SOURCE
357 and req_source is not None
358 and _is_concrete_artifact_pointer(req_source)
359 ):
360 src_path = req_source
361 elif (
362 req_name is not None
363 and AnsibleCollectionRef.is_valid_collection_name(req_name)
364 ):
365 req_type = 'galaxy'
366 elif (
367 req_name is not None
368 and _is_concrete_artifact_pointer(req_name)
369 ):
370 src_path, req_name = req_name, None
371 else:
372 dir_tip_tmpl = ( # NOTE: leading LFs are for concat
373 '\n\nTip: Make sure you are pointing to the right '
374 'subdirectory — `{src!s}` looks like a directory '
375 'but it is neither a collection, nor a namespace '
376 'dir.'
377 )
378
379 if req_source is not None and os.path.isdir(req_source):
380 tip = dir_tip_tmpl.format(src=req_source)
381 elif req_name is not None and os.path.isdir(req_name):
382 tip = dir_tip_tmpl.format(src=req_name)
383 elif req_name:
384 tip = '\n\nCould not find {0}.'.format(req_name)
385 else:
386 tip = ''
387
388 raise AnsibleError( # NOTE: I'd prefer a ValueError instead
389 'Neither the collection requirement entry key '
390 "'name', nor 'source' point to a concrete "
391 "resolvable collection artifact. Also 'name' is "
392 'not an FQCN. A valid collection name must be in '
393 'the format <namespace>.<collection>. Please make '
394 'sure that the namespace and the collection name '
395 'contain characters from [a-zA-Z0-9_] only.'
396 '{extra_tip!s}'.format(extra_tip=tip),
397 )
398
399 if req_type is None:
400 if _is_git_url(src_path):
401 req_type = 'git'
402 req_source = src_path
403 elif _is_http_url(src_path):
404 req_type = 'url'
405 req_source = src_path
406 elif _is_file_path(src_path):
407 req_type = 'file'
408 req_source = src_path
409 elif _is_collection_dir(src_path):
410 if _is_installed_collection_dir(src_path) and _is_collection_src_dir(src_path):
411 # Note that ``download`` requires a dir with a ``galaxy.yml`` and fails if it
412 # doesn't exist, but if a ``MANIFEST.json`` also exists, it would be used
413 # instead of the ``galaxy.yml``.
414 raise AnsibleError(
415 u"Collection requirement at '{path!s}' has both a {manifest_json!s} "
416 u"file and a {galaxy_yml!s}.\nThe requirement must either be an installed "
417 u"collection directory or a source collection directory, not both.".
418 format(
419 path=to_text(src_path, errors='surrogate_or_strict'),
420 manifest_json=to_text(_MANIFEST_JSON),
421 galaxy_yml=to_text(_GALAXY_YAML),
422 )
423 )
424 req_type = 'dir'
425 req_source = src_path
426 elif _is_collection_namespace_dir(src_path):
427 req_name = None # No name for a virtual req or "namespace."?
428 req_type = 'subdirs'
429 req_source = src_path
430 else:
431 raise AnsibleError( # NOTE: this is never supposed to be hit
432 'Failed to automatically detect the collection '
433 'requirement type.',
434 )
435
436 if req_type not in {'file', 'galaxy', 'git', 'url', 'dir', 'subdirs'}:
437 raise AnsibleError(
438 "The collection requirement entry key 'type' must be "
439 'one of file, galaxy, git, dir, subdirs, or url.'
440 )
441
442 if req_name is None and req_type == 'galaxy':
443 raise AnsibleError(
444 'Collections requirement entry should contain '
445 "the key 'name' if it's requested from a Galaxy-like "
446 'index server.',
447 )
448
449 if req_type != 'galaxy' and req_source is None:
450 req_source, req_name = req_name, None
451
452 if (
453 req_type == 'galaxy' and
454 isinstance(req_source, GalaxyAPI) and
455 not _is_http_url(req_source.api_server)
456 ):
457 raise AnsibleError(
458 "Collections requirement 'source' entry should contain "
459 'a valid Galaxy API URL but it does not: {not_url!s} '
460 'is not an HTTP URL.'.
461 format(not_url=req_source.api_server),
462 )
463
464 if (
465 req_type == 'dir'
466 and isinstance(req_source, str)
467 and req_source.endswith(os.path.sep)
468 ):
469 req_source = req_source.rstrip(os.path.sep)
470
471 tmp_inst_req = cls(req_name, req_version, req_source, req_type, req_signature_sources)
472
473 if req_type not in {'galaxy', 'subdirs'} and req_name is None:
474 req_name = art_mgr.get_direct_collection_fqcn(tmp_inst_req) # TODO: fix the cache key in artifacts manager?
475
476 if req_type not in {'galaxy', 'subdirs'} and req_version == '*':
477 req_version = art_mgr.get_direct_collection_version(tmp_inst_req)
478
479 return cls(
480 req_name, req_version,
481 req_source, req_type,
482 req_signature_sources,
483 )
484
485 def __repr__(self) -> str:
486 return (
487 '<{self!s} of type {coll_type!r} from {src!s}>'.
488 format(self=self, coll_type=self.type, src=self.src or 'Galaxy')
489 )
490
491 def __str__(self) -> str:
492 return to_native(self.__unicode__())
493
494 def __unicode__(self) -> str:
495 if self.fqcn is None:
496 return (
497 f'{self.type} collection from a Git repo' if self.is_scm
498 else f'{self.type} collection from a namespace'
499 )
500
501 return (
502 u'{fqcn!s}:{ver!s}'.
503 format(fqcn=to_text(self.fqcn), ver=to_text(self.ver))
504 )
505
506 @property
507 def may_have_offline_galaxy_info(self) -> bool:
508 if self.fqcn is None:
509 # Virtual collection
510 return False
511 elif not self.is_dir or self.src is None or not _is_collection_dir(self.src):
512 # Not a dir or isn't on-disk
513 return False
514 return True
515
516 def construct_galaxy_info_path(self, b_collection_path: bytes) -> bytes:
517 if not self.may_have_offline_galaxy_info and not self.type == 'galaxy':
518 raise TypeError('Only installed collections from a Galaxy server have offline Galaxy info')
519
520 # Store Galaxy metadata adjacent to the namespace of the collection
521 # Chop off the last two parts of the path (/ns/coll) to get the dir containing the ns
522 b_src = to_bytes(b_collection_path, errors='surrogate_or_strict')
523 b_path_parts = b_src.split(to_bytes(os.path.sep))[0:-2]
524 b_metadata_dir = to_bytes(os.path.sep).join(b_path_parts)
525
526 # ns.coll-1.0.0.info
527 b_dir_name = to_bytes(f"{self.namespace}.{self.name}-{self.ver}.info", errors="surrogate_or_strict")
528
529 # collections/ansible_collections/ns.coll-1.0.0.info/GALAXY.yml
530 return os.path.join(b_metadata_dir, b_dir_name, _SOURCE_METADATA_FILE)
531
532 def _get_separate_ns_n_name(self): # FIXME: use LRU cache
533 return self.fqcn.split('.')
534
535 @property
536 def namespace(self) -> str:
537 if self.is_virtual:
538 raise TypeError(f'{self.type} collections do not have a namespace')
539
540 return self._get_separate_ns_n_name()[0]
541
542 @property
543 def name(self) -> str:
544 if self.is_virtual:
545 raise TypeError(f'{self.type} collections do not have a name')
546
547 return self._get_separate_ns_n_name()[-1]
548
549 @property
550 def canonical_package_id(self) -> str:
551 if not self.is_virtual or self.type == "requires_ansible":
552 return to_native(self.fqcn)
553
554 return (
555 '<virtual namespace from {src!s} of type {src_type!s}>'.
556 format(src=to_native(self.src), src_type=to_native(self.type))
557 )
558
559 @property
560 def is_virtual(self) -> bool:
561 return self.is_scm or self.is_subdirs
562
563 @property
564 def is_file(self) -> bool:
565 return self.type == 'file'
566
567 @property
568 def is_dir(self) -> bool:
569 return self.type == 'dir'
570
571 @property
572 def namespace_collection_paths(self) -> list[str]:
573 return [
574 to_native(path)
575 for path in _find_collections_in_subdirs(self.src)
576 ]
577
578 @property
579 def is_subdirs(self) -> bool:
580 return self.type == 'subdirs'
581
582 @property
583 def is_url(self) -> bool:
584 return self.type == 'url'
585
586 @property
587 def is_scm(self) -> bool:
588 return self.type == 'git'
589
590 @property
591 def is_concrete_artifact(self) -> bool:
592 return self.type in {'git', 'url', 'file', 'dir', 'subdirs'}
593
594 @property
595 def is_online_index_pointer(self) -> bool:
596 return not self.is_concrete_artifact
597
598 @property
599 def is_pinned(self) -> bool:
600 """Indicate if the version set is considered pinned.
601
602 This essentially computes whether the version field of the current
603 requirement explicitly requests a specific version and not an allowed
604 version range.
605
606 It is then used to help the resolvelib-based dependency resolver judge
607 whether it's acceptable to consider a pre-release candidate version
608 despite pre-release installs not being requested by the end-user
609 explicitly.
610
611 See https://github.com/ansible/ansible/pull/81606 for extra context.
612 """
613 version_spec_start_char = self.ver[0]
614 return version_spec_start_char.isdigit() or not (
615 version_spec_start_char.startswith(('<', '>', '!', '*'))
616 )
617
618 @property
619 def source_info(self) -> dict[str, object] | None:
620 return self._source_info
621
622
623 RequirementNamedTuple = namedtuple('Requirement', ('fqcn', 'ver', 'src', 'type', 'signature_sources')) # type: ignore[name-match]
624
625
626 CandidateNamedTuple = namedtuple('Candidate', ('fqcn', 'ver', 'src', 'type', 'signatures')) # type: ignore[name-match]
627
628
629 class Requirement(
630 _ComputedReqKindsMixin,
631 RequirementNamedTuple,
632 ):
633 """An abstract requirement request."""
634
635 def __new__(cls, *args: object, **kwargs: object) -> t.Self:
636 self = RequirementNamedTuple.__new__(cls, *args, **kwargs)
637 return self
638
639 def __init__(self, *args: object, **kwargs: object) -> None:
640 super(Requirement, self).__init__()
641 # NOTE: Hack to display the origin of impossible collection requirements when requires_ansible is incompatible
642 # e.g. Requirement ns.col -> ns.col:$ver -> Requirement ns.dep -> ns.dep:$ver -> Requirement ansible-core<2.19
643 # - ResolutionImpossible.causes[0].requirement is Requirement ansible-core<2.19
644 # - ResolutionImpossible.causes[0].parent is Candidate ns.dep:$ver
645 # - ResolutionImpossible.causes[0].parent._requirements[0] is Requirement ns.dep
646 # - ResolutionImpossible.causes[0].parent._requirements[0]._parent is Candidate ns.col:$ver
647 self._parent: Candidate | None = None
648
649
650 class Candidate(
651 _ComputedReqKindsMixin,
652 CandidateNamedTuple,
653 ):
654 """A concrete collection candidate with its version resolved."""
655
656 def __new__(cls, *args: object, **kwargs: object) -> t.Self:
657 self = CandidateNamedTuple.__new__(cls, *args, **kwargs)
658 return self
659
660 def __init__(self, *args: object, **kwargs: object) -> None:
661 super(Candidate, self).__init__()
662 # NOTE: Hack to display the origin of impossible collection requirements when requires_ansible is incompatible
663 self._requirements: list[Requirement] = []
664
665 def with_signatures_repopulated(self) -> Candidate:
666 """Populate a new Candidate instance with Galaxy signatures.
667 :raises AnsibleAssertionError: If the supplied candidate is not sourced from a Galaxy-like index.
668 """
669 if self.type != 'galaxy':
670 raise AnsibleAssertionError(f"Invalid collection type for {self!r}: unable to get signatures from a galaxy server.")
671
672 signatures = self.src.get_collection_signatures(self.namespace, self.name, self.ver)
673 return self.__class__(self.fqcn, self.ver, self.src, self.type, frozenset([*self.signatures, *signatures]))
674
675
676 class AnsibleRequirement(Requirement):
677 def __init__(self, *args: object, **kwargs: object) -> None:
678 super(AnsibleRequirement, self).__init__()
679
680 self.has_candidate: None | Candidate
681 if _does_collection_support_ansible_version(self.ver, __version__):
682 self.has_candidate = Candidate("ansible-core", __version__, None, "requires_ansible", None)
683 else:
684 self.has_candidate = None
685
686 @classmethod
687 def from_collection(cls, concrete_art_mgr: ConcreteArtifactsManager, candidate: Candidate) -> None | t.Self:
688 """
689 Create a Requirement from a collection Candidate's requires_ansible metadata.
690 """
691 if (
692 C.COLLECTIONS_ON_ANSIBLE_VERSION_MISMATCH == "ignore"
693 or candidate.is_virtual
694 or candidate.type == "requires_ansible"
695 ):
696 return None
697
698 if candidate.type == 'galaxy':
699 requires_ansible = (candidate.src.requires_ansible.get(candidate.fqcn) or {}).get(candidate.ver)
700 else:
701 requires_ansible = concrete_art_mgr.get_direct_requires_ansible(candidate)
702
703 if requires_ansible is None:
704 display.warning(f"{candidate!s} does not have requires_ansible metadata.")
705 return None
706
707 # Passing the "fqcn" attribute so __unicode__ doesn't need to be overridden.
708 res = cls("ansible-core", requires_ansible, None, "requires_ansible", None)
709 res._parent = candidate
710 return res
711
712 def is_satisfied_by(self, candidate: Candidate) -> bool:
713 return self.has_candidate == candidate