1"""
2APIs exposing metadata from third-party Python packages.
3
4This codebase is shared between importlib.metadata in the stdlib
5and importlib_metadata in PyPI. See
6https://github.com/python/importlib_metadata/wiki/Development-Methodology
7for more detail.
8"""
9
10from __future__ import annotations
11
12import abc
13import collections
14import email
15import functools
16import itertools
17import operator
18import os
19import pathlib
20import posixpath
21import re
22import sys
23import textwrap
24import types
25from collections.abc import Callable, Iterable, Mapping
26from contextlib import suppress
27from importlib import import_module
28from importlib.abc import MetaPathFinder
29from itertools import starmap
30from typing import Any, TypeVar
31
32from ._collections import FreezableDefaultDict, Pair
33from ._compat import (
34 NullFinder,
35 install,
36 localize,
37)
38from ._functools import apply, compose, method_cache, noop, pass_none, passthrough
39from ._itertools import always_iterable, bucket, unique_everseen
40from ._meta import (
41 IDistribution,
42 IPackagePath,
43 PackageMetadata,
44 SimplePath,
45)
46from .compat import py311
47
48__all__ = [
49 'Distribution',
50 'DistributionFinder',
51 'IDistribution',
52 'IPackagePath',
53 'MetadataNotFound',
54 'PackageMetadata',
55 'PackageNotFoundError',
56 'PackagePath',
57 'SimplePath',
58 'distribution',
59 'distributions',
60 'entry_points',
61 'files',
62 'metadata',
63 'packages_distributions',
64 'requires',
65 'version',
66]
67
68
69_D = TypeVar('_D', bound=IDistribution)
70
71
72class PackageNotFoundError(ModuleNotFoundError):
73 """The package was not found."""
74
75 def __str__(self) -> str:
76 return f"No package metadata was found for {self.name}"
77
78 @property
79 def name(self) -> str: # type: ignore[override] # make readonly
80 (name,) = self.args
81 return name
82
83
84class MetadataNotFound(FileNotFoundError):
85 """No metadata file is present in the distribution."""
86
87
88class Sectioned:
89 """
90 A simple entry point config parser for performance
91
92 >>> for item in Sectioned.read(Sectioned._sample):
93 ... print(item)
94 Pair(name='sec1', value='# comments ignored')
95 Pair(name='sec1', value='a = 1')
96 Pair(name='sec1', value='b = 2')
97 Pair(name='sec2', value='a = 2')
98
99 >>> res = Sectioned.section_pairs(Sectioned._sample)
100 >>> item = next(res)
101 >>> item.name
102 'sec1'
103 >>> item.value
104 Pair(name='a', value='1')
105 >>> item = next(res)
106 >>> item.value
107 Pair(name='b', value='2')
108 >>> item = next(res)
109 >>> item.name
110 'sec2'
111 >>> item.value
112 Pair(name='a', value='2')
113 >>> list(res)
114 []
115 """
116
117 _sample = textwrap.dedent(
118 """
119 [sec1]
120 # comments ignored
121 a = 1
122 b = 2
123
124 [sec2]
125 a = 2
126 """
127 ).lstrip()
128
129 @classmethod
130 def section_pairs(cls, text):
131 return (
132 section._replace(value=Pair.parse(section.value))
133 for section in cls.read(text, filter_=cls.valid)
134 if section.name is not None
135 )
136
137 @staticmethod
138 def read(text, filter_=None):
139 lines = filter(filter_, map(str.strip, text.splitlines()))
140 name = None
141 for value in lines:
142 section_match = value.startswith('[') and value.endswith(']')
143 if section_match:
144 name = value.strip('[]')
145 continue
146 yield Pair(name, value)
147
148 @staticmethod
149 def valid(line: str):
150 return line and not line.startswith('#')
151
152
153class _EntryPointMatch(types.SimpleNamespace):
154 module: str
155 attr: str
156 extras: str
157
158
159class EntryPoint:
160 """An entry point as defined by Python packaging conventions.
161
162 See `the packaging docs on entry points
163 <https://packaging.python.org/specifications/entry-points/>`_
164 for more information.
165
166 >>> ep = EntryPoint(
167 ... name=None, group=None, value='package.module:attr [extra1, extra2]')
168 >>> ep.module
169 'package.module'
170 >>> ep.attr
171 'attr'
172 >>> ep.extras
173 ['extra1', 'extra2']
174
175 If the value package or module are not valid identifiers, a
176 ValueError is raised on access.
177
178 >>> EntryPoint(name=None, group=None, value='invalid-name').module
179 Traceback (most recent call last):
180 ...
181 ValueError: ('Invalid object reference...invalid-name...
182 >>> EntryPoint(name=None, group=None, value='invalid-name').attr
183 Traceback (most recent call last):
184 ...
185 ValueError: ('Invalid object reference...invalid-name...
186 >>> EntryPoint(name=None, group=None, value='invalid-name').extras
187 Traceback (most recent call last):
188 ...
189 ValueError: ('Invalid object reference...invalid-name...
190
191 Construction never raises; the value is validated only when
192 accessed or loaded.
193
194 >>> ep = EntryPoint(name=None, group=None, value='invalid-name')
195 >>> ep.load()
196 Traceback (most recent call last):
197 ...
198 ValueError: ('Invalid object reference...invalid-name...
199
200 """
201
202 pattern = re.compile(
203 r'(?P<module>[\w.]+)\s*'
204 r'(:\s*(?P<attr>[\w.]+)\s*)?'
205 r'((?P<extras>\[.*\])\s*)?$'
206 )
207 """
208 A regular expression describing the syntax for an entry point,
209 which might look like:
210
211 - module
212 - package.module
213 - package.module:attribute
214 - package.module:object.attribute
215 - package.module:attr [extra1, extra2]
216
217 Other combinations are possible as well.
218
219 The expression is lenient about whitespace around the ':',
220 following the attr, and following any extras.
221 """
222
223 name: str
224 value: str
225 group: str
226
227 dist: IDistribution | None = None
228
229 def __init__(self, name: str, value: str, group: str) -> None:
230 vars(self).update(name=name, value=value, group=group)
231
232 def load(self) -> Any:
233 """Load the entry point from its definition. If only a module
234 is indicated by the value, return that module. Otherwise,
235 return the named object.
236 """
237 module = import_module(self.module)
238 attrs = filter(None, (self.attr or '').split('.'))
239 return functools.reduce(getattr, attrs, module)
240
241 @property
242 def module(self) -> str:
243 return self._match.module
244
245 @property
246 def attr(self) -> str:
247 return self._match.attr
248
249 @property
250 def extras(self) -> list[str]:
251 return re.findall(r'\w+', self._match.extras or '')
252
253 @functools.cached_property
254 def _match(self) -> _EntryPointMatch:
255 match = self.pattern.match(self.value)
256 if not match:
257 raise ValueError(
258 'Invalid object reference. '
259 'See https://packaging.python.org'
260 '/en/latest/specifications/entry-points/#data-model',
261 self.value,
262 )
263 return _EntryPointMatch(**match.groupdict())
264
265 def _for(self, dist):
266 vars(self).update(dist=dist)
267 return self
268
269 def matches(self, **params):
270 """
271 EntryPoint matches the given parameters.
272
273 >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]')
274 >>> ep.matches(group='foo')
275 True
276 >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]')
277 True
278 >>> ep.matches(group='foo', name='other')
279 False
280 >>> ep.matches()
281 True
282 >>> ep.matches(extras=['extra1', 'extra2'])
283 True
284 >>> ep.matches(module='bing')
285 True
286 >>> ep.matches(attr='bong')
287 True
288 """
289 self._disallow_dist(params)
290 attrs = (getattr(self, param) for param in params)
291 return all(map(operator.eq, params.values(), attrs))
292
293 @staticmethod
294 def _disallow_dist(params):
295 """
296 Querying by dist is not allowed (dist objects are not comparable).
297 >>> EntryPoint(name='fan', value='fav', group='fag').matches(dist='foo')
298 Traceback (most recent call last):
299 ...
300 ValueError: "dist" is not suitable for matching...
301 """
302 if "dist" in params:
303 raise ValueError(
304 '"dist" is not suitable for matching. '
305 "Instead, use Distribution.entry_points.select() on a "
306 "located distribution."
307 )
308
309 def _key(self):
310 return self.name, self.value, self.group
311
312 def __lt__(self, other):
313 return self._key() < other._key()
314
315 def __eq__(self, other):
316 return self._key() == other._key()
317
318 def __setattr__(self, name, value):
319 raise AttributeError("EntryPoint objects are immutable.")
320
321 def __repr__(self):
322 return (
323 f'EntryPoint(name={self.name!r}, value={self.value!r}, '
324 f'group={self.group!r})'
325 )
326
327 def __hash__(self) -> int:
328 return hash(self._key())
329
330
331class EntryPoints(tuple):
332 """
333 An immutable collection of selectable EntryPoint objects.
334 """
335
336 __slots__ = ()
337
338 def __getitem__(self, name: str) -> EntryPoint: # type: ignore[override] # Work with str instead of int
339 """
340 Get the EntryPoint in self matching name.
341 """
342 try:
343 return next(iter(self.select(name=name)))
344 except StopIteration:
345 raise KeyError(name)
346
347 def __repr__(self):
348 """
349 Repr with classname and tuple constructor to
350 signal that we deviate from regular tuple behavior.
351 """
352 return f'{self.__class__.__name__}({tuple(self)!r})'
353
354 def select(self, **params) -> EntryPoints:
355 """
356 Select entry points from self that match the
357 given parameters (typically group and/or name).
358 """
359 return EntryPoints(ep for ep in self if ep.matches(**params))
360
361 @property
362 def names(self) -> set[str]:
363 """
364 Return the set of all names of all entry points.
365 """
366 return {ep.name for ep in self}
367
368 @property
369 def groups(self) -> set[str]:
370 """
371 Return the set of all groups of all entry points.
372 """
373 return {ep.group for ep in self}
374
375 @classmethod
376 def _from_text_for(cls, text, dist):
377 return cls(ep._for(dist) for ep in cls._from_text(text))
378
379 @staticmethod
380 def _from_text(text):
381 return (
382 EntryPoint(name=item.value.name, value=item.value.value, group=item.name)
383 for item in Sectioned.section_pairs(text or '')
384 )
385
386
387class PackagePath(pathlib.PurePosixPath):
388 """A reference to a path in a package"""
389
390 hash: FileHash | None
391 size: int
392 dist: IDistribution
393
394 def read_text(self, encoding: str = 'utf-8') -> str:
395 return self.locate().read_text(encoding=encoding)
396
397 def read_binary(self) -> bytes:
398 return self.locate().read_bytes()
399
400 def locate(self) -> SimplePath:
401 """Return a path-like object for this path"""
402 return self.dist.locate_file(self)
403
404
405class FileHash:
406 def __init__(self, spec: str) -> None:
407 self.mode, _, self.value = spec.partition('=')
408
409 def __repr__(self) -> str:
410 return f'<FileHash mode: {self.mode} value: {self.value}>'
411
412
413def _identify_dist(
414 accessor: Callable[[Distribution], str],
415) -> Callable[[Distribution], str]:
416 """
417 Decorate a required metadata accessor to identify the distribution
418 in the error raised when its field is absent.
419 """
420
421 @functools.wraps(accessor)
422 def wrapper(self: Distribution) -> str:
423 try:
424 return accessor(self)
425 except KeyError as exc:
426 (field,) = exc.args
427 raise KeyError(f'Metadata field {field} not present in {self}') from None
428
429 return wrapper
430
431
432class Distribution(metaclass=abc.ABCMeta):
433 """
434 An abstract Python distribution package.
435
436 Custom providers may derive from this class and define
437 the abstract methods to provide a concrete implementation
438 for their environment. Some providers may opt to override
439 the default implementation of some properties to bypass
440 the file-reading mechanism.
441 """
442
443 @abc.abstractmethod
444 def read_text(self, filename) -> str | None:
445 """Attempt to load metadata file given by the name.
446
447 Python distribution metadata is organized by blobs of text
448 typically represented as "files" in the metadata directory
449 (e.g. package-1.0.dist-info). These files include things
450 like:
451
452 - METADATA: The distribution metadata including fields
453 like Name and Version and Description.
454 - entry_points.txt: A series of entry points as defined in
455 `the entry points spec <https://packaging.python.org/en/latest/specifications/entry-points/#file-format>`_.
456 - RECORD: A record of files according to
457 `this recording spec <https://packaging.python.org/en/latest/specifications/recording-installed-packages/#the-record-file>`_.
458
459 A package may provide any set of files, including those
460 not listed here or none at all.
461
462 :param filename: The name of the file in the distribution info.
463 :return: The text if found, otherwise None.
464 """
465
466 @abc.abstractmethod
467 def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
468 """
469 Given a path to a file in this distribution, return a SimplePath
470 to it.
471
472 This method is used by callers of ``Distribution.files()`` to
473 locate files within the distribution. If it's possible for a
474 Distribution to represent files in the distribution as
475 ``SimplePath`` objects, it should implement this method
476 to resolve such objects.
477
478 Some Distribution providers may elect not to resolve SimplePath
479 objects within the distribution by raising a
480 NotImplementedError, but consumers of such a Distribution would
481 be unable to invoke ``Distribution.files()``.
482 """
483
484 @classmethod
485 @apply(localize.dist)
486 def from_name(cls, name: str) -> Distribution:
487 """Return the Distribution for the given package name.
488
489 :param name: The name of the distribution package to search for.
490 :return: The Distribution instance (or subclass thereof) for the named
491 package, if found.
492 :raises PackageNotFoundError: When the named package's distribution
493 metadata cannot be found.
494 :raises ValueError: When an invalid value is supplied for name.
495 """
496 if not name:
497 raise ValueError("A distribution name is required.")
498 try:
499 return next(iter(cls._prefer_valid(cls.discover(name=name))))
500 except StopIteration:
501 raise PackageNotFoundError(name) from None
502
503 @classmethod
504 @apply(functools.partial(map, localize.dist))
505 def discover(
506 cls, *, context: DistributionFinder.Context | None = None, **kwargs
507 ) -> Iterable[Distribution]:
508 """Return an iterable of Distribution objects for all packages.
509
510 Pass a ``context`` or pass keyword arguments for constructing
511 a context.
512
513 :context: A ``DistributionFinder.Context`` object.
514 :return: Iterable of Distribution objects for packages matching
515 the context.
516 """
517 if context and kwargs:
518 raise ValueError("cannot accept context and kwargs")
519 context = context or DistributionFinder.Context(**kwargs)
520 return itertools.chain.from_iterable(
521 resolver(context) for resolver in cls._discover_resolvers()
522 )
523
524 @staticmethod
525 def _prefer_valid(dists: Iterable[_D]) -> Iterable[_D]:
526 """
527 Prefer (move to the front) distributions that have metadata.
528
529 Ref python/importlib_resources#489.
530 """
531
532 buckets = bucket(dists, _safe_has_metadata)
533 return itertools.chain(buckets[True], buckets[False])
534
535 @staticmethod
536 def at(path: str | os.PathLike[str]) -> Distribution:
537 """Return a Distribution for the indicated metadata path.
538
539 :param path: a string or path-like object
540 :return: a concrete Distribution instance for the path
541 """
542 return PathDistribution(pathlib.Path(path))
543
544 @staticmethod
545 def _discover_resolvers():
546 """Search the meta_path for resolvers (MetadataPathFinders)."""
547 declared = (
548 getattr(finder, 'find_distributions', None) for finder in sys.meta_path
549 )
550 return filter(None, declared)
551
552 @property
553 @apply(localize.message)
554 def metadata(self) -> PackageMetadata:
555 """Return the parsed metadata for this Distribution.
556
557 The returned object will have keys that name the various bits of
558 metadata per the
559 `Core metadata specifications <https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata>`_.
560
561 Custom providers may provide the METADATA file or override this
562 property.
563
564 :raises MetadataNotFound: If no metadata file is present.
565 """
566
567 text = self._metadata_text()
568 return self._assemble_message(self._ensure_metadata_present(text))
569
570 def _metadata_text(self) -> str | None:
571 """
572 The metadata text, if any.
573
574 Separate from ``metadata`` so that ``_has_metadata`` can name
575 the same files without repeating them and without paying to
576 parse what it finds.
577 """
578 return (
579 self.read_text('METADATA')
580 or self.read_text('PKG-INFO')
581 # This last clause is here to support old egg-info files. Its
582 # effect is to just end up using the PathDistribution's self._path
583 # (which points to the egg-info file) attribute unchanged.
584 or self.read_text('')
585 )
586
587 def _has_metadata(self) -> bool:
588 """
589 Whether this distribution supplies metadata.
590
591 Reads the metadata, as the interface offers nothing cheaper:
592 ``locate_file`` resolves against the package root and not the
593 metadata, and every other member loads the metadata or parses
594 it. A subclass able to detect the metadata without reading it
595 should override this (python/importlib_metadata#534).
596 """
597 return bool(self._metadata_text())
598
599 @staticmethod
600 def _assemble_message(text: str) -> PackageMetadata:
601 # deferred for performance (python/cpython#109829)
602 from . import _adapters
603
604 return _adapters.Message(email.message_from_string(text))
605
606 def _ensure_metadata_present(self, text: str | None) -> str:
607 if text is not None:
608 return text
609
610 raise MetadataNotFound('No package metadata was found.')
611
612 @property
613 @_identify_dist
614 def name(self) -> str:
615 """Return the 'Name' metadata for the distribution package."""
616 return self.metadata['Name']
617
618 @property
619 def _normalized_name(self):
620 """Return a normalized version of the name."""
621 return Prepared.normalize(self.name)
622
623 @property
624 @_identify_dist
625 def version(self) -> str:
626 """Return the 'Version' metadata for the distribution package."""
627 return self.metadata['Version']
628
629 @property
630 def entry_points(self) -> EntryPoints:
631 """
632 Return EntryPoints for this distribution.
633
634 Custom providers may provide the ``entry_points.txt`` file
635 or override this property.
636 """
637 return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)
638
639 @property
640 @apply(pass_none(compose(list, functools.partial(map, localize.package_path))))
641 def files(self) -> list[IPackagePath] | None:
642 """Files in this distribution.
643
644 :return: List of PackagePath-like objects for this distribution or None
645
646 Result is `None` if the metadata file that enumerates files
647 (i.e. RECORD for dist-info, or installed-files.txt or
648 SOURCES.txt for egg-info) is missing.
649 Result may be empty if the metadata exists but is empty.
650
651 Custom providers are recommended to provide a "RECORD" file (in
652 ``read_text``) or override this property to allow for callers to be
653 able to resolve filenames provided by the package.
654 """
655
656 def make_file(name, hash=None, size_str=None):
657 result = PackagePath(name)
658 result.hash = FileHash(hash) if hash else None
659 result.size = int(size_str) if size_str else None
660 result.dist = self
661 return result
662
663 @pass_none
664 def make_files(lines):
665 # Delay csv import, since Distribution.files is not as widely used
666 # as other parts of importlib.metadata
667 import csv
668
669 return starmap(make_file, csv.reader(lines))
670
671 @pass_none
672 def skip_missing_files(package_paths):
673 return list(filter(lambda path: path.locate().exists(), package_paths))
674
675 return skip_missing_files(
676 make_files(
677 self._read_files_distinfo()
678 or self._read_files_egginfo_installed()
679 or self._read_files_egginfo_sources()
680 )
681 )
682
683 def _read_files_distinfo(self):
684 """
685 Read the lines of RECORD.
686 """
687 text = self.read_text('RECORD')
688 return text and text.splitlines()
689
690 def _read_files_egginfo_installed(self):
691 """
692 Read installed-files.txt and return lines in a similar
693 CSV-parsable format as RECORD: each file must be placed
694 relative to the site-packages directory and must also be
695 quoted (since file names can contain literal commas).
696
697 This file is written when the package is installed by pip,
698 but it might not be written for other installation methods.
699 Assume the file is accurate if it exists.
700 """
701 text = self.read_text('installed-files.txt')
702 # Prepend the .egg-info/ subdir to the lines in this file.
703 # But this subdir is only available from PathDistribution's
704 # self._path.
705 subdir = getattr(self, '_path', None)
706 if not text or not subdir:
707 return
708
709 paths = (
710 py311
711 .relative_fix((subdir / name).resolve())
712 .relative_to(self.locate_file('').resolve(), walk_up=True)
713 .as_posix()
714 for name in text.splitlines()
715 )
716 return map('"{}"'.format, paths)
717
718 def _read_files_egginfo_sources(self):
719 """
720 Read SOURCES.txt and return lines in a similar CSV-parsable
721 format as RECORD: each file name must be quoted (since it
722 might contain literal commas).
723
724 Note that SOURCES.txt is not a reliable source for what
725 files are installed by a package. This file is generated
726 for a source archive, and the files that are present
727 there (e.g. setup.py) may not correctly reflect the files
728 that are present after the package has been installed.
729 """
730 text = self.read_text('SOURCES.txt')
731 return text and map('"{}"'.format, text.splitlines())
732
733 @property
734 def requires(self) -> list[str] | None:
735 """Generated requirements specified for this Distribution"""
736 reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
737 return reqs and list(reqs)
738
739 def _read_dist_info_reqs(self):
740 return self.metadata.get_all('Requires-Dist')
741
742 def _read_egg_info_reqs(self):
743 source = self.read_text('requires.txt')
744 return pass_none(self._deps_from_requires_text)(source)
745
746 @classmethod
747 def _deps_from_requires_text(cls, source):
748 return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))
749
750 @staticmethod
751 def _convert_egg_info_reqs_to_simple_reqs(sections):
752 """
753 Historically, setuptools would solicit and store 'extra'
754 requirements, including those with environment markers,
755 in separate sections. More modern tools expect each
756 dependency to be defined separately, with any relevant
757 extras and environment markers attached directly to that
758 requirement. This method converts the former to the
759 latter. See _test_deps_from_requires_text for an example.
760 """
761
762 def make_condition(name):
763 return name and f'extra == "{name}"'
764
765 def quoted_marker(section):
766 section = section or ''
767 extra, _sep, markers = section.partition(':')
768 if extra and markers:
769 markers = f'({markers})'
770 conditions = list(filter(None, [markers, make_condition(extra)]))
771 return '; ' + ' and '.join(conditions) if conditions else ''
772
773 def url_req_space(req):
774 """
775 PEP 508 requires a space between the url_spec and the quoted_marker.
776 Ref python/importlib_metadata#357.
777 """
778 # '@' is uniquely indicative of a url_req.
779 return ' ' * ('@' in req)
780
781 for section in sections:
782 space = url_req_space(section.value)
783 yield section.value + space + quoted_marker(section.name)
784
785 @property
786 def origin(self):
787 return self._load_json('direct_url.json')
788
789 def _load_json(self, filename):
790 # Deferred for performance (python/importlib_metadata#503)
791 import json
792
793 return pass_none(json.loads)(
794 self.read_text(filename),
795 object_hook=lambda data: types.SimpleNamespace(**data),
796 )
797
798
799class DistributionFinder(MetaPathFinder):
800 """
801 A MetaPathFinder capable of discovering installed distributions.
802
803 Custom providers should implement this interface in order to
804 supply metadata.
805 """
806
807 class Context:
808 """
809 Keyword arguments presented by the caller to
810 ``distributions()`` or ``Distribution.discover()``
811 to narrow the scope of a search for distributions
812 in all DistributionFinders.
813
814 Each DistributionFinder may expect any parameters
815 and should attempt to honor the canonical
816 parameters defined below when appropriate.
817
818 This mechanism gives a custom provider a means to
819 solicit additional details from the caller beyond
820 "name" and "path" when searching distributions.
821 For example, imagine a provider that exposes suites
822 of packages in either a "public" or "private" ``realm``.
823 A caller may wish to query only for distributions in
824 a particular realm and could call
825 ``distributions(realm="private")`` to signal to the
826 custom provider to only include distributions from that
827 realm.
828 """
829
830 name = None
831 """
832 Specific name for which a distribution finder should match.
833 A name of ``None`` matches all distributions.
834 """
835
836 def __init__(self, **kwargs):
837 vars(self).update(kwargs)
838
839 @property
840 def path(self) -> list[str]:
841 """
842 The sequence of directory path that a distribution finder
843 should search.
844
845 Typically refers to Python installed package paths such as
846 "site-packages" directories and defaults to ``sys.path``.
847 """
848 return vars(self).get('path', sys.path)
849
850 @abc.abstractmethod
851 def find_distributions(self, context=Context()) -> Iterable[Distribution]:
852 """
853 Find distributions.
854
855 Return an iterable of all Distribution instances capable of
856 loading the metadata for packages matching the ``context``,
857 a DistributionFinder.Context instance.
858 """
859
860
861@passthrough
862def _clear_after_fork(cached):
863 """Ensure ``func`` clears cached state after ``fork`` when supported.
864
865 ``FastPath`` caches zip-backed ``pathlib.Path`` objects that retain a
866 reference to the parent's open ``ZipFile`` handle. Re-using a cached
867 instance in a forked child can therefore resurrect invalid file pointers
868 and trigger ``BadZipFile``/``OSError`` failures (python/importlib_metadata#520).
869 Registering ``cache_clear`` with ``os.register_at_fork`` keeps each process
870 on its own cache.
871 """
872 getattr(os, 'register_at_fork', noop)(after_in_child=cached.cache_clear)
873
874
875class FastPath:
876 """
877 Micro-optimized class for searching a root for children.
878
879 Root is a path on the file system that may contain metadata
880 directories either as natural directories or within a zip file.
881
882 >>> FastPath('').children()
883 ['...']
884
885 FastPath objects are cached and recycled for any given root.
886
887 >>> FastPath('foobar') is FastPath('foobar')
888 True
889 """
890
891 @_clear_after_fork # type: ignore[misc]
892 @functools.lru_cache
893 def __new__(cls, root):
894 return super().__new__(cls)
895
896 def __init__(self, root):
897 self.root = root
898
899 def joinpath(self, child):
900 return pathlib.Path(self.root, child)
901
902 def children(self):
903 with suppress(Exception):
904 return os.listdir(self.root or '.')
905 with suppress(Exception):
906 return self.zip_children()
907 return []
908
909 def zip_children(self):
910 # deferred for performance (python/importlib_metadata#502)
911 from zipp.compat.overlay import zipfile
912
913 zip_path = zipfile.Path(self.root)
914 names = zip_path.root.namelist()
915 self.joinpath = zip_path.joinpath
916
917 return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names)
918
919 def search(self, name):
920 return self.lookup(self.mtime).search(name)
921
922 @property
923 def mtime(self):
924 with suppress(OSError):
925 return os.stat(self.root).st_mtime
926 self.lookup.cache_clear()
927
928 @method_cache
929 def lookup(self, mtime):
930 return Lookup(self)
931
932
933class Lookup:
934 """
935 A micro-optimized class for searching a (fast) path for metadata.
936 """
937
938 def __init__(self, path: FastPath):
939 """
940 Calculate all of the children representing metadata.
941
942 From the children in the path, calculate early all of the
943 children that appear to represent metadata (infos) or legacy
944 metadata (eggs).
945 """
946
947 base = os.path.basename(path.root).lower()
948 base_is_egg = base.endswith(".egg")
949 self.infos = FreezableDefaultDict(list)
950 self.eggs = FreezableDefaultDict(list)
951
952 for child in path.children():
953 low = child.lower()
954 if low.endswith((".dist-info", ".egg-info")):
955 # rpartition is faster than splitext and suitable for this purpose.
956 name = low.rpartition(".")[0].partition("-")[0]
957 normalized = Prepared.normalize(name)
958 self.infos[normalized].append(path.joinpath(child))
959 elif base_is_egg and low == "egg-info":
960 name = base.rpartition(".")[0].partition("-")[0]
961 legacy_normalized = Prepared.legacy_normalize(name)
962 self.eggs[legacy_normalized].append(path.joinpath(child))
963
964 self.infos.freeze()
965 self.eggs.freeze()
966
967 def search(self, prepared: Prepared):
968 """
969 Yield all infos and eggs matching the Prepared query.
970 """
971 infos = (
972 self.infos[prepared.normalized]
973 if prepared
974 else itertools.chain.from_iterable(self.infos.values())
975 )
976 eggs = (
977 self.eggs[prepared.legacy_normalized]
978 if prepared
979 else itertools.chain.from_iterable(self.eggs.values())
980 )
981 return itertools.chain(infos, eggs)
982
983
984class Prepared:
985 """
986 A prepared search query for metadata on a possibly-named package.
987
988 Pre-calculates the normalization to prevent repeated operations.
989
990 >>> none = Prepared(None)
991 >>> none.normalized
992 >>> none.legacy_normalized
993 >>> bool(none)
994 False
995 >>> sample = Prepared('Sample__Pkg-name.foo')
996 >>> sample.normalized
997 'sample_pkg_name_foo'
998 >>> sample.legacy_normalized
999 'sample__pkg_name.foo'
1000 >>> bool(sample)
1001 True
1002 """
1003
1004 normalized = None
1005 legacy_normalized = None
1006
1007 def __init__(self, name: str | None):
1008 self.name = name
1009 if name is None:
1010 return
1011 self.normalized = self.normalize(name)
1012 self.legacy_normalized = self.legacy_normalize(name)
1013
1014 @staticmethod
1015 def normalize(name):
1016 """
1017 PEP 503 normalization plus dashes as underscores.
1018 """
1019 return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_')
1020
1021 @staticmethod
1022 def legacy_normalize(name):
1023 """
1024 Normalize the package name as found in the convention in
1025 older packaging tools versions and specs.
1026 """
1027 return name.lower().replace('-', '_')
1028
1029 def __bool__(self):
1030 return bool(self.name)
1031
1032
1033@install
1034class MetadataPathFinder(NullFinder, DistributionFinder):
1035 """A degenerate finder for distribution packages on the file system.
1036
1037 This finder supplies only a find_distributions() method for versions
1038 of Python that do not have a PathFinder find_distributions().
1039 """
1040
1041 @classmethod
1042 def find_distributions(
1043 cls, context=DistributionFinder.Context()
1044 ) -> Iterable[PathDistribution]:
1045 """
1046 Find distributions.
1047
1048 Return an iterable of all Distribution instances capable of
1049 loading the metadata for packages matching ``context.name``
1050 (or all names if ``None`` indicated) along the paths in the list
1051 of directories ``context.path``.
1052 """
1053 found = cls._search_paths(context.name, context.path)
1054 return map(PathDistribution, found)
1055
1056 @classmethod
1057 def _search_paths(cls, name, paths):
1058 """Find metadata directories in paths heuristically."""
1059 prepared = Prepared(name)
1060 return itertools.chain.from_iterable(
1061 path.search(prepared) for path in map(FastPath, paths)
1062 )
1063
1064 @classmethod
1065 def invalidate_caches(cls) -> None:
1066 FastPath.__new__.cache_clear()
1067
1068
1069class PathDistribution(Distribution):
1070 def __init__(self, path: SimplePath) -> None:
1071 """Construct a distribution.
1072
1073 :param path: SimplePath indicating the metadata directory.
1074 """
1075 self._path = path
1076
1077 def __str__(self) -> str:
1078 """
1079 Render as the metadata path, identifying the distribution
1080 even when its metadata cannot name it.
1081
1082 >>> str(Distribution.at('foo-1.0.dist-info'))
1083 'foo-1.0.dist-info'
1084 """
1085 return str(self._path)
1086
1087 def read_text(self, filename: str | os.PathLike[str]) -> str | None:
1088 with suppress(
1089 FileNotFoundError,
1090 IsADirectoryError,
1091 KeyError,
1092 NotADirectoryError,
1093 PermissionError,
1094 ):
1095 return self._path.joinpath(filename).read_text(encoding='utf-8')
1096
1097 return None
1098
1099 read_text.__doc__ = Distribution.read_text.__doc__
1100
1101 def _has_metadata(self) -> bool:
1102 """
1103 Detect the metadata file without opening it
1104 (python/importlib_metadata#534).
1105
1106 The last clause is for an old-style egg-info file, whose
1107 metadata is the distribution's own path; a metadata directory
1108 is not itself metadata. ``SimplePath`` doesn't name
1109 ``is_file``, but only these legacy paths reach that clause and
1110 they arrive as a ``pathlib.Path`` or a ``zipfile.Path``, both
1111 of which supply it.
1112 """
1113 return (
1114 self._path.joinpath('METADATA').exists()
1115 or self._path.joinpath('PKG-INFO').exists()
1116 or self._path.is_file() # type: ignore[attr-defined]
1117 )
1118
1119 def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
1120 return self._path.parent / path
1121
1122 @property
1123 def _normalized_name(self):
1124 """
1125 Performance optimization: where possible, resolve the
1126 normalized name from the file system path.
1127 """
1128 stem = os.path.basename(str(self._path))
1129 return (
1130 pass_none(Prepared.normalize)(self._name_from_stem(stem))
1131 or super()._normalized_name
1132 )
1133
1134 @staticmethod
1135 def _name_from_stem(stem):
1136 """
1137 >>> PathDistribution._name_from_stem('foo-3.0.egg-info')
1138 'foo'
1139 >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info')
1140 'CherryPy'
1141 >>> PathDistribution._name_from_stem('face.egg-info')
1142 'face'
1143 >>> PathDistribution._name_from_stem('foo.bar')
1144 """
1145 filename, ext = os.path.splitext(stem)
1146 if ext not in ('.dist-info', '.egg-info'):
1147 return
1148 name, _sep, _rest = filename.partition('-')
1149 return name
1150
1151
1152def distribution(distribution_name: str) -> IDistribution:
1153 """Get the ``Distribution`` instance for the named package.
1154
1155 :param distribution_name: The name of the distribution package as a string.
1156 :return: A ``Distribution`` instance (or subclass thereof).
1157 """
1158 return Distribution.from_name(distribution_name)
1159
1160
1161def distributions(**kwargs) -> Iterable[IDistribution]:
1162 """Get all ``Distribution`` instances in the current environment.
1163
1164 :return: An iterable of ``Distribution`` instances.
1165 """
1166 return Distribution.discover(**kwargs)
1167
1168
1169def metadata(distribution_name: str) -> PackageMetadata:
1170 """Get the metadata for the named package.
1171
1172 :param distribution_name: The name of the distribution package to query.
1173 :return: A PackageMetadata containing the parsed metadata.
1174 :raises MetadataNotFound: If no metadata file is present in the distribution.
1175 """
1176 return Distribution.from_name(distribution_name).metadata
1177
1178
1179def version(distribution_name: str) -> str:
1180 """Get the version string for the named package.
1181
1182 :param distribution_name: The name of the distribution package to query.
1183 :return: The version string for the package as defined in the package's
1184 "Version" metadata key.
1185 """
1186 return distribution(distribution_name).version
1187
1188
1189def _safe_has_metadata(dist: IDistribution) -> bool:
1190 """
1191 ``dist._has_metadata()``, for a distribution that may not supply it.
1192
1193 A provider's own ``Distribution`` subclass derives from
1194 ``importlib.metadata`` and is passed through unadapted (#486), so
1195 it has none; read its metadata as the default would. It supplies
1196 no ``_metadata_text`` either, hence the unbound call.
1197
1198 Such a distribution cannot be asked for ``metadata`` behind a trap
1199 instead. The ``MetadataNotFound`` it raises is the one from
1200 ``importlib.metadata``, a different class from this package's,
1201 which no trap of ours would catch.
1202 """
1203 with suppress(AttributeError):
1204 return dist._has_metadata() # type: ignore[attr-defined]
1205 return bool(Distribution._metadata_text(dist)) # type: ignore[arg-type]
1206
1207
1208_unique = functools.partial(
1209 unique_everseen,
1210 key=operator.attrgetter('_normalized_name'),
1211)
1212"""
1213Wrapper for ``distributions`` to return unique distributions by name.
1214"""
1215
1216
1217def entry_points(**params) -> EntryPoints:
1218 """Return EntryPoint objects for all installed packages.
1219
1220 Pass selection parameters (group or name) to filter the
1221 result to entry points matching those properties (see
1222 EntryPoints.select()).
1223
1224 :return: EntryPoints for all installed packages.
1225 """
1226 eps = itertools.chain.from_iterable(
1227 dist.entry_points
1228 for dist in _unique(Distribution._prefer_valid(distributions()))
1229 )
1230 return EntryPoints(eps).select(**params)
1231
1232
1233def files(distribution_name: str) -> list[IPackagePath] | None:
1234 """Return a list of files for the named package.
1235
1236 :param distribution_name: The name of the distribution package to query.
1237 :return: List of files composing the distribution.
1238 """
1239 return distribution(distribution_name).files
1240
1241
1242def requires(distribution_name: str) -> list[str] | None:
1243 """
1244 Return a list of requirements for the named package.
1245
1246 :return: An iterable of requirements, suitable for
1247 packaging.requirement.Requirement.
1248 """
1249 return distribution(distribution_name).requires
1250
1251
1252def packages_distributions() -> Mapping[str, list[str]]:
1253 """
1254 Return a mapping of top-level packages to their
1255 distributions.
1256
1257 >>> import collections.abc
1258 >>> pkgs = packages_distributions()
1259 >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
1260 True
1261 """
1262 pkg_to_dist = collections.defaultdict(list)
1263 for dist in distributions():
1264 for pkg in _top_level_declared(dist) or _top_level_inferred(dist):
1265 pkg_to_dist[pkg].append(dist.metadata['Name'])
1266 return dict(pkg_to_dist)
1267
1268
1269def _top_level_declared(dist):
1270 return (dist.read_text('top_level.txt') or '').split()
1271
1272
1273def _topmost(name: IPackagePath) -> str | None:
1274 """
1275 Return the top-most parent as long as there is a parent.
1276 """
1277 top, *rest = name.parts
1278 return top if rest else None
1279
1280
1281def _get_toplevel_name(name: IPackagePath) -> str:
1282 """
1283 Infer a possibly importable module name from a name presumed on
1284 sys.path.
1285
1286 >>> _get_toplevel_name(PackagePath('foo.py'))
1287 'foo'
1288 >>> _get_toplevel_name(PackagePath('foo'))
1289 'foo'
1290 >>> _get_toplevel_name(PackagePath('foo.pyc'))
1291 'foo'
1292 >>> _get_toplevel_name(PackagePath('foo/__init__.py'))
1293 'foo'
1294 >>> _get_toplevel_name(PackagePath('foo.pth'))
1295 'foo.pth'
1296 >>> _get_toplevel_name(PackagePath('foo.dist-info'))
1297 'foo.dist-info'
1298 """
1299 # Defer import of inspect for performance (python/cpython#118761)
1300 import inspect
1301
1302 return _topmost(name) or inspect.getmodulename(name) or str(name)
1303
1304
1305def _top_level_inferred(dist):
1306 opt_names = set(map(_get_toplevel_name, always_iterable(dist.files)))
1307
1308 def importable_name(name):
1309 return '.' not in name
1310
1311 return filter(importable_name, opt_names)