Debian Codegraph @

third_party/python/setuptools/pkg_resources/__init__.py

raw
1 """
2 Package resource API
3 --------------------
4
5 A resource is a logical file contained within a package, or a logical
6 subdirectory thereof. The package resource API expects resource names
7 to have their path parts separated with ``/``, *not* whatever the local
8 path separator is. Do not use os.path operations to manipulate resource
9 names being passed into the API.
10
11 The package resource API is designed to work with normal filesystem packages,
12 .egg files, and unpacked .egg files. It can also work in a limited way with
13 .zip files and with custom PEP 302 loaders that support the ``get_data()``
14 method.
15
16 This module is deprecated. Users are directed to :mod:`importlib.resources`,
17 :mod:`importlib.metadata` and :pypi:`packaging` instead.
18 """
19
20 from __future__ import annotations
21
22 import sys
23
24 if sys.version_info < (3, 8): # noqa: UP036 # Check for unsupported versions
25 raise RuntimeError("Python 3.8 or later is required")
26
27 import _imp
28 import collections
29 import email.parser
30 import errno
31 import functools
32 import importlib
33 import importlib.abc
34 import importlib.machinery
35 import inspect
36 import io
37 import ntpath
38 import operator
39 import os
40 import pkgutil
41 import platform
42 import plistlib
43 import posixpath
44 import re
45 import stat
46 import tempfile
47 import textwrap
48 import time
49 import types
50 import warnings
51 import zipfile
52 import zipimport
53 from pkgutil import get_importer
54 from typing import (
55 TYPE_CHECKING,
56 Any,
57 BinaryIO,
58 Callable,
59 Dict,
60 Iterable,
61 Iterator,
62 Literal,
63 Mapping,
64 MutableSequence,
65 NamedTuple,
66 NoReturn,
67 Protocol,
68 Tuple,
69 TypeVar,
70 Union,
71 overload,
72 )
73
74 sys.path.extend(((vendor_path := os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setuptools', '_vendor')) not in sys.path) * [vendor_path]) # fmt: skip
75 # workaround for #4476
76 sys.modules.pop('backports', None)
77
78 # capture these to bypass sandboxing
79 from os import open as os_open, utime # isort: skip
80 from os.path import isdir, split # isort: skip
81
82 try:
83 from os import mkdir, rename, unlink
84
85 WRITE_SUPPORT = True
86 except ImportError:
87 # no write support, probably under GAE
88 WRITE_SUPPORT = False
89
90 import packaging.markers
91 import packaging.requirements
92 import packaging.specifiers
93 import packaging.utils
94 import packaging.version
95 from jaraco.text import drop_comment, join_continuation, yield_lines
96 from platformdirs import user_cache_dir as _user_cache_dir
97
98 if TYPE_CHECKING:
99 from _typeshed import BytesPath, StrOrBytesPath, StrPath
100 from _typeshed.importlib import LoaderProtocol
101 from typing_extensions import Self, TypeAlias
102
103 warnings.warn(
104 "pkg_resources is deprecated as an API. "
105 "See https://setuptools.pypa.io/en/latest/pkg_resources.html",
106 DeprecationWarning,
107 stacklevel=2,
108 )
109
110 _T = TypeVar("_T")
111 _DistributionT = TypeVar("_DistributionT", bound="Distribution")
112 # Type aliases
113 _NestedStr: TypeAlias = Union[str, Iterable[Union[str, Iterable["_NestedStr"]]]]
114 _StrictInstallerType: TypeAlias = Callable[["Requirement"], "_DistributionT"]
115 _InstallerType: TypeAlias = Callable[["Requirement"], Union["Distribution", None]]
116 _PkgReqType: TypeAlias = Union[str, "Requirement"]
117 _EPDistType: TypeAlias = Union["Distribution", _PkgReqType]
118 _MetadataType: TypeAlias = Union["IResourceProvider", None]
119 _ResolvedEntryPoint: TypeAlias = Any # Can be any attribute in the module
120 _ResourceStream: TypeAlias = Any # TODO / Incomplete: A readable file-like object
121 # Any object works, but let's indicate we expect something like a module (optionally has __loader__ or __file__)
122 _ModuleLike: TypeAlias = Union[object, types.ModuleType]
123 # Any: Should be _ModuleLike but we end up with issues where _ModuleLike doesn't have _ZipLoaderModule's __loader__
124 _ProviderFactoryType: TypeAlias = Callable[[Any], "IResourceProvider"]
125 _DistFinderType: TypeAlias = Callable[[_T, str, bool], Iterable["Distribution"]]
126 _NSHandlerType: TypeAlias = Callable[[_T, str, str, types.ModuleType], Union[str, None]]
127 _AdapterT = TypeVar(
128 "_AdapterT", _DistFinderType[Any], _ProviderFactoryType, _NSHandlerType[Any]
129 )
130
131
132 class _ZipLoaderModule(Protocol):
133 __loader__: zipimport.zipimporter
134
135
136 _PEP440_FALLBACK = re.compile(r"^v?(?P<safe>(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.I)
137
138
139 class PEP440Warning(RuntimeWarning):
140 """
141 Used when there is an issue with a version or specifier not complying with
142 PEP 440.
143 """
144
145
146 parse_version = packaging.version.Version
147
148 _state_vars: dict[str, str] = {}
149
150
151 def _declare_state(vartype: str, varname: str, initial_value: _T) -> _T:
152 _state_vars[varname] = vartype
153 return initial_value
154
155
156 def __getstate__() -> dict[str, Any]:
157 state = {}
158 g = globals()
159 for k, v in _state_vars.items():
160 state[k] = g['_sget_' + v](g[k])
161 return state
162
163
164 def __setstate__(state: dict[str, Any]) -> dict[str, Any]:
165 g = globals()
166 for k, v in state.items():
167 g['_sset_' + _state_vars[k]](k, g[k], v)
168 return state
169
170
171 def _sget_dict(val):
172 return val.copy()
173
174
175 def _sset_dict(key, ob, state):
176 ob.clear()
177 ob.update(state)
178
179
180 def _sget_object(val):
181 return val.__getstate__()
182
183
184 def _sset_object(key, ob, state):
185 ob.__setstate__(state)
186
187
188 _sget_none = _sset_none = lambda *args: None
189
190
191 def get_supported_platform():
192 """Return this platform's maximum compatible version.
193
194 distutils.util.get_platform() normally reports the minimum version
195 of macOS that would be required to *use* extensions produced by
196 distutils. But what we want when checking compatibility is to know the
197 version of macOS that we are *running*. To allow usage of packages that
198 explicitly require a newer version of macOS, we must also know the
199 current version of the OS.
200
201 If this condition occurs for any other platform with a version in its
202 platform strings, this function should be extended accordingly.
203 """
204 plat = get_build_platform()
205 m = macosVersionString.match(plat)
206 if m is not None and sys.platform == "darwin":
207 try:
208 plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
209 except ValueError:
210 # not macOS
211 pass
212 return plat
213
214
215 __all__ = [
216 # Basic resource access and distribution/entry point discovery
217 'require',
218 'run_script',
219 'get_provider',
220 'get_distribution',
221 'load_entry_point',
222 'get_entry_map',
223 'get_entry_info',
224 'iter_entry_points',
225 'resource_string',
226 'resource_stream',
227 'resource_filename',
228 'resource_listdir',
229 'resource_exists',
230 'resource_isdir',
231 # Environmental control
232 'declare_namespace',
233 'working_set',
234 'add_activation_listener',
235 'find_distributions',
236 'set_extraction_path',
237 'cleanup_resources',
238 'get_default_cache',
239 # Primary implementation classes
240 'Environment',
241 'WorkingSet',
242 'ResourceManager',
243 'Distribution',
244 'Requirement',
245 'EntryPoint',
246 # Exceptions
247 'ResolutionError',
248 'VersionConflict',
249 'DistributionNotFound',
250 'UnknownExtra',
251 'ExtractionError',
252 # Warnings
253 'PEP440Warning',
254 # Parsing functions and string utilities
255 'parse_requirements',
256 'parse_version',
257 'safe_name',
258 'safe_version',
259 'get_platform',
260 'compatible_platforms',
261 'yield_lines',
262 'split_sections',
263 'safe_extra',
264 'to_filename',
265 'invalid_marker',
266 'evaluate_marker',
267 # filesystem utilities
268 'ensure_directory',
269 'normalize_path',
270 # Distribution "precedence" constants
271 'EGG_DIST',
272 'BINARY_DIST',
273 'SOURCE_DIST',
274 'CHECKOUT_DIST',
275 'DEVELOP_DIST',
276 # "Provider" interfaces, implementations, and registration/lookup APIs
277 'IMetadataProvider',
278 'IResourceProvider',
279 'FileMetadata',
280 'PathMetadata',
281 'EggMetadata',
282 'EmptyProvider',
283 'empty_provider',
284 'NullProvider',
285 'EggProvider',
286 'DefaultProvider',
287 'ZipProvider',
288 'register_finder',
289 'register_namespace_handler',
290 'register_loader_type',
291 'fixup_namespace_packages',
292 'get_importer',
293 # Warnings
294 'PkgResourcesDeprecationWarning',
295 # Deprecated/backward compatibility only
296 'run_main',
297 'AvailableDistributions',
298 ]
299
300
301 class ResolutionError(Exception):
302 """Abstract base for dependency resolution errors"""
303
304 def __repr__(self) -> str:
305 return self.__class__.__name__ + repr(self.args)
306
307
308 class VersionConflict(ResolutionError):
309 """
310 An already-installed version conflicts with the requested version.
311
312 Should be initialized with the installed Distribution and the requested
313 Requirement.
314 """
315
316 _template = "{self.dist} is installed but {self.req} is required"
317
318 @property
319 def dist(self) -> Distribution:
320 return self.args[0]
321
322 @property
323 def req(self) -> Requirement:
324 return self.args[1]
325
326 def report(self):
327 return self._template.format(**locals())
328
329 def with_context(
330 self, required_by: set[Distribution | str]
331 ) -> Self | ContextualVersionConflict:
332 """
333 If required_by is non-empty, return a version of self that is a
334 ContextualVersionConflict.
335 """
336 if not required_by:
337 return self
338 args = self.args + (required_by,)
339 return ContextualVersionConflict(*args)
340
341
342 class ContextualVersionConflict(VersionConflict):
343 """
344 A VersionConflict that accepts a third parameter, the set of the
345 requirements that required the installed Distribution.
346 """
347
348 _template = VersionConflict._template + ' by {self.required_by}'
349
350 @property
351 def required_by(self) -> set[str]:
352 return self.args[2]
353
354
355 class DistributionNotFound(ResolutionError):
356 """A requested distribution was not found"""
357
358 _template = (
359 "The '{self.req}' distribution was not found "
360 "and is required by {self.requirers_str}"
361 )
362
363 @property
364 def req(self) -> Requirement:
365 return self.args[0]
366
367 @property
368 def requirers(self) -> set[str] | None:
369 return self.args[1]
370
371 @property
372 def requirers_str(self):
373 if not self.requirers:
374 return 'the application'
375 return ', '.join(self.requirers)
376
377 def report(self):
378 return self._template.format(**locals())
379
380 def __str__(self) -> str:
381 return self.report()
382
383
384 class UnknownExtra(ResolutionError):
385 """Distribution doesn't have an "extra feature" of the given name"""
386
387
388 _provider_factories: dict[type[_ModuleLike], _ProviderFactoryType] = {}
389
390 PY_MAJOR = '{}.{}'.format(*sys.version_info)
391 EGG_DIST = 3
392 BINARY_DIST = 2
393 SOURCE_DIST = 1
394 CHECKOUT_DIST = 0
395 DEVELOP_DIST = -1
396
397
398 def register_loader_type(
399 loader_type: type[_ModuleLike], provider_factory: _ProviderFactoryType
400 ) -> None:
401 """Register `provider_factory` to make providers for `loader_type`
402
403 `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
404 and `provider_factory` is a function that, passed a *module* object,
405 returns an ``IResourceProvider`` for that module.
406 """
407 _provider_factories[loader_type] = provider_factory
408
409
410 @overload
411 def get_provider(moduleOrReq: str) -> IResourceProvider: ...
412 @overload
413 def get_provider(moduleOrReq: Requirement) -> Distribution: ...
414 def get_provider(moduleOrReq: str | Requirement) -> IResourceProvider | Distribution:
415 """Return an IResourceProvider for the named module or requirement"""
416 if isinstance(moduleOrReq, Requirement):
417 return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
418 try:
419 module = sys.modules[moduleOrReq]
420 except KeyError:
421 __import__(moduleOrReq)
422 module = sys.modules[moduleOrReq]
423 loader = getattr(module, '__loader__', None)
424 return _find_adapter(_provider_factories, loader)(module)
425
426
427 @functools.lru_cache(maxsize=None)
428 def _macos_vers():
429 version = platform.mac_ver()[0]
430 # fallback for MacPorts
431 if version == '':
432 plist = '/System/Library/CoreServices/SystemVersion.plist'
433 if os.path.exists(plist):
434 with open(plist, 'rb') as fh:
435 plist_content = plistlib.load(fh)
436 if 'ProductVersion' in plist_content:
437 version = plist_content['ProductVersion']
438 return version.split('.')
439
440
441 def _macos_arch(machine):
442 return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
443
444
445 def get_build_platform():
446 """Return this platform's string for platform-specific distributions
447
448 XXX Currently this is the same as ``distutils.util.get_platform()``, but it
449 needs some hacks for Linux and macOS.
450 """
451 from sysconfig import get_platform
452
453 plat = get_platform()
454 if sys.platform == "darwin" and not plat.startswith('macosx-'):
455 try:
456 version = _macos_vers()
457 machine = os.uname()[4].replace(" ", "_")
458 return "macosx-%d.%d-%s" % (
459 int(version[0]),
460 int(version[1]),
461 _macos_arch(machine),
462 )
463 except ValueError:
464 # if someone is running a non-Mac darwin system, this will fall
465 # through to the default implementation
466 pass
467 return plat
468
469
470 macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
471 darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
472 # XXX backward compat
473 get_platform = get_build_platform
474
475
476 def compatible_platforms(provided: str | None, required: str | None) -> bool:
477 """Can code for the `provided` platform run on the `required` platform?
478
479 Returns true if either platform is ``None``, or the platforms are equal.
480
481 XXX Needs compatibility checks for Linux and other unixy OSes.
482 """
483 if provided is None or required is None or provided == required:
484 # easy case
485 return True
486
487 # macOS special cases
488 reqMac = macosVersionString.match(required)
489 if reqMac:
490 provMac = macosVersionString.match(provided)
491
492 # is this a Mac package?
493 if not provMac:
494 # this is backwards compatibility for packages built before
495 # setuptools 0.6. All packages built after this point will
496 # use the new macOS designation.
497 provDarwin = darwinVersionString.match(provided)
498 if provDarwin:
499 dversion = int(provDarwin.group(1))
500 macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
501 if (
502 dversion == 7
503 and macosversion >= "10.3"
504 or dversion == 8
505 and macosversion >= "10.4"
506 ):
507 return True
508 # egg isn't macOS or legacy darwin
509 return False
510
511 # are they the same major version and machine type?
512 if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3):
513 return False
514
515 # is the required OS major update >= the provided one?
516 if int(provMac.group(2)) > int(reqMac.group(2)):
517 return False
518
519 return True
520
521 # XXX Linux and other platforms' special cases should go here
522 return False
523
524
525 @overload
526 def get_distribution(dist: _DistributionT) -> _DistributionT: ...
527 @overload
528 def get_distribution(dist: _PkgReqType) -> Distribution: ...
529 def get_distribution(dist: Distribution | _PkgReqType) -> Distribution:
530 """Return a current distribution object for a Requirement or string"""
531 if isinstance(dist, str):
532 dist = Requirement.parse(dist)
533 if isinstance(dist, Requirement):
534 dist = get_provider(dist)
535 if not isinstance(dist, Distribution):
536 raise TypeError("Expected str, Requirement, or Distribution", dist)
537 return dist
538
539
540 def load_entry_point(dist: _EPDistType, group: str, name: str) -> _ResolvedEntryPoint:
541 """Return `name` entry point of `group` for `dist` or raise ImportError"""
542 return get_distribution(dist).load_entry_point(group, name)
543
544
545 @overload
546 def get_entry_map(
547 dist: _EPDistType, group: None = None
548 ) -> dict[str, dict[str, EntryPoint]]: ...
549 @overload
550 def get_entry_map(dist: _EPDistType, group: str) -> dict[str, EntryPoint]: ...
551 def get_entry_map(dist: _EPDistType, group: str | None = None):
552 """Return the entry point map for `group`, or the full entry map"""
553 return get_distribution(dist).get_entry_map(group)
554
555
556 def get_entry_info(dist: _EPDistType, group: str, name: str) -> EntryPoint | None:
557 """Return the EntryPoint object for `group`+`name`, or ``None``"""
558 return get_distribution(dist).get_entry_info(group, name)
559
560
561 class IMetadataProvider(Protocol):
562 def has_metadata(self, name: str) -> bool:
563 """Does the package's distribution contain the named metadata?"""
564 ...
565
566 def get_metadata(self, name: str) -> str:
567 """The named metadata resource as a string"""
568 ...
569
570 def get_metadata_lines(self, name: str) -> Iterator[str]:
571 """Yield named metadata resource as list of non-blank non-comment lines
572
573 Leading and trailing whitespace is stripped from each line, and lines
574 with ``#`` as the first non-blank character are omitted."""
575 ...
576
577 def metadata_isdir(self, name: str) -> bool:
578 """Is the named metadata a directory? (like ``os.path.isdir()``)"""
579 ...
580
581 def metadata_listdir(self, name: str) -> list[str]:
582 """List of metadata names in the directory (like ``os.listdir()``)"""
583 ...
584
585 def run_script(self, script_name: str, namespace: dict[str, Any]) -> None:
586 """Execute the named script in the supplied namespace dictionary"""
587 ...
588
589
590 class IResourceProvider(IMetadataProvider, Protocol):
591 """An object that provides access to package resources"""
592
593 def get_resource_filename(
594 self, manager: ResourceManager, resource_name: str
595 ) -> str:
596 """Return a true filesystem path for `resource_name`
597
598 `manager` must be a ``ResourceManager``"""
599 ...
600
601 def get_resource_stream(
602 self, manager: ResourceManager, resource_name: str
603 ) -> _ResourceStream:
604 """Return a readable file-like object for `resource_name`
605
606 `manager` must be a ``ResourceManager``"""
607 ...
608
609 def get_resource_string(
610 self, manager: ResourceManager, resource_name: str
611 ) -> bytes:
612 """Return the contents of `resource_name` as :obj:`bytes`
613
614 `manager` must be a ``ResourceManager``"""
615 ...
616
617 def has_resource(self, resource_name: str) -> bool:
618 """Does the package contain the named resource?"""
619 ...
620
621 def resource_isdir(self, resource_name: str) -> bool:
622 """Is the named resource a directory? (like ``os.path.isdir()``)"""
623 ...
624
625 def resource_listdir(self, resource_name: str) -> list[str]:
626 """List of resource names in the directory (like ``os.listdir()``)"""
627 ...
628
629
630 class WorkingSet:
631 """A collection of active distributions on sys.path (or a similar list)"""
632
633 def __init__(self, entries: Iterable[str] | None = None) -> None:
634 """Create working set from list of path entries (default=sys.path)"""
635 self.entries: list[str] = []
636 self.entry_keys: dict[str | None, list[str]] = {}
637 self.by_key: dict[str, Distribution] = {}
638 self.normalized_to_canonical_keys: dict[str, str] = {}
639 self.callbacks: list[Callable[[Distribution], object]] = []
640
641 if entries is None:
642 entries = sys.path
643
644 for entry in entries:
645 self.add_entry(entry)
646
647 @classmethod
648 def _build_master(cls):
649 """
650 Prepare the master working set.
651 """
652 ws = cls()
653 try:
654 from __main__ import __requires__
655 except ImportError:
656 # The main program does not list any requirements
657 return ws
658
659 # ensure the requirements are met
660 try:
661 ws.require(__requires__)
662 except VersionConflict:
663 return cls._build_from_requirements(__requires__)
664
665 return ws
666
667 @classmethod
668 def _build_from_requirements(cls, req_spec):
669 """
670 Build a working set from a requirement spec. Rewrites sys.path.
671 """
672 # try it without defaults already on sys.path
673 # by starting with an empty path
674 ws = cls([])
675 reqs = parse_requirements(req_spec)
676 dists = ws.resolve(reqs, Environment())
677 for dist in dists:
678 ws.add(dist)
679
680 # add any missing entries from sys.path
681 for entry in sys.path:
682 if entry not in ws.entries:
683 ws.add_entry(entry)
684
685 # then copy back to sys.path
686 sys.path[:] = ws.entries
687 return ws
688
689 def add_entry(self, entry: str) -> None:
690 """Add a path item to ``.entries``, finding any distributions on it
691
692 ``find_distributions(entry, True)`` is used to find distributions
693 corresponding to the path entry, and they are added. `entry` is
694 always appended to ``.entries``, even if it is already present.
695 (This is because ``sys.path`` can contain the same value more than
696 once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
697 equal ``sys.path``.)
698 """
699 self.entry_keys.setdefault(entry, [])
700 self.entries.append(entry)
701 for dist in find_distributions(entry, True):
702 self.add(dist, entry, False)
703
704 def __contains__(self, dist: Distribution) -> bool:
705 """True if `dist` is the active distribution for its project"""
706 return self.by_key.get(dist.key) == dist
707
708 def find(self, req: Requirement) -> Distribution | None:
709 """Find a distribution matching requirement `req`
710
711 If there is an active distribution for the requested project, this
712 returns it as long as it meets the version requirement specified by
713 `req`. But, if there is an active distribution for the project and it
714 does *not* meet the `req` requirement, ``VersionConflict`` is raised.
715 If there is no active distribution for the requested project, ``None``
716 is returned.
717 """
718 dist = self.by_key.get(req.key)
719
720 if dist is None:
721 canonical_key = self.normalized_to_canonical_keys.get(req.key)
722
723 if canonical_key is not None:
724 req.key = canonical_key
725 dist = self.by_key.get(canonical_key)
726
727 if dist is not None and dist not in req:
728 # XXX add more info
729 raise VersionConflict(dist, req)
730 return dist
731
732 def iter_entry_points(
733 self, group: str, name: str | None = None
734 ) -> Iterator[EntryPoint]:
735 """Yield entry point objects from `group` matching `name`
736
737 If `name` is None, yields all entry points in `group` from all
738 distributions in the working set, otherwise only ones matching
739 both `group` and `name` are yielded (in distribution order).
740 """
741 return (
742 entry
743 for dist in self
744 for entry in dist.get_entry_map(group).values()
745 if name is None or name == entry.name
746 )
747
748 def run_script(self, requires: str, script_name: str) -> None:
749 """Locate distribution for `requires` and run `script_name` script"""
750 ns = sys._getframe(1).f_globals
751 name = ns['__name__']
752 ns.clear()
753 ns['__name__'] = name
754 self.require(requires)[0].run_script(script_name, ns)
755
756 def __iter__(self) -> Iterator[Distribution]:
757 """Yield distributions for non-duplicate projects in the working set
758
759 The yield order is the order in which the items' path entries were
760 added to the working set.
761 """
762 seen = set()
763 for item in self.entries:
764 if item not in self.entry_keys:
765 # workaround a cache issue
766 continue
767
768 for key in self.entry_keys[item]:
769 if key not in seen:
770 seen.add(key)
771 yield self.by_key[key]
772
773 def add(
774 self,
775 dist: Distribution,
776 entry: str | None = None,
777 insert: bool = True,
778 replace: bool = False,
779 ) -> None:
780 """Add `dist` to working set, associated with `entry`
781
782 If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
783 On exit from this routine, `entry` is added to the end of the working
784 set's ``.entries`` (if it wasn't already present).
785
786 `dist` is only added to the working set if it's for a project that
787 doesn't already have a distribution in the set, unless `replace=True`.
788 If it's added, any callbacks registered with the ``subscribe()`` method
789 will be called.
790 """
791 if insert:
792 dist.insert_on(self.entries, entry, replace=replace)
793
794 if entry is None:
795 entry = dist.location
796 keys = self.entry_keys.setdefault(entry, [])
797 keys2 = self.entry_keys.setdefault(dist.location, [])
798 if not replace and dist.key in self.by_key:
799 # ignore hidden distros
800 return
801
802 self.by_key[dist.key] = dist
803 normalized_name = packaging.utils.canonicalize_name(dist.key)
804 self.normalized_to_canonical_keys[normalized_name] = dist.key
805 if dist.key not in keys:
806 keys.append(dist.key)
807 if dist.key not in keys2:
808 keys2.append(dist.key)
809 self._added_new(dist)
810
811 @overload
812 def resolve(
813 self,
814 requirements: Iterable[Requirement],
815 env: Environment | None,
816 installer: _StrictInstallerType[_DistributionT],
817 replace_conflicting: bool = False,
818 extras: tuple[str, ...] | None = None,
819 ) -> list[_DistributionT]: ...
820 @overload
821 def resolve(
822 self,
823 requirements: Iterable[Requirement],
824 env: Environment | None = None,
825 *,
826 installer: _StrictInstallerType[_DistributionT],
827 replace_conflicting: bool = False,
828 extras: tuple[str, ...] | None = None,
829 ) -> list[_DistributionT]: ...
830 @overload
831 def resolve(
832 self,
833 requirements: Iterable[Requirement],
834 env: Environment | None = None,
835 installer: _InstallerType | None = None,
836 replace_conflicting: bool = False,
837 extras: tuple[str, ...] | None = None,
838 ) -> list[Distribution]: ...
839 def resolve(
840 self,
841 requirements: Iterable[Requirement],
842 env: Environment | None = None,
843 installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None,
844 replace_conflicting: bool = False,
845 extras: tuple[str, ...] | None = None,
846 ) -> list[Distribution] | list[_DistributionT]:
847 """List all distributions needed to (recursively) meet `requirements`
848
849 `requirements` must be a sequence of ``Requirement`` objects. `env`,
850 if supplied, should be an ``Environment`` instance. If
851 not supplied, it defaults to all distributions available within any
852 entry or distribution in the working set. `installer`, if supplied,
853 will be invoked with each requirement that cannot be met by an
854 already-installed distribution; it should return a ``Distribution`` or
855 ``None``.
856
857 Unless `replace_conflicting=True`, raises a VersionConflict exception
858 if
859 any requirements are found on the path that have the correct name but
860 the wrong version. Otherwise, if an `installer` is supplied it will be
861 invoked to obtain the correct version of the requirement and activate
862 it.
863
864 `extras` is a list of the extras to be used with these requirements.
865 This is important because extra requirements may look like `my_req;
866 extra = "my_extra"`, which would otherwise be interpreted as a purely
867 optional requirement. Instead, we want to be able to assert that these
868 requirements are truly required.
869 """
870
871 # set up the stack
872 requirements = list(requirements)[::-1]
873 # set of processed requirements
874 processed = set()
875 # key -> dist
876 best: dict[str, Distribution] = {}
877 to_activate: list[Distribution] = []
878
879 req_extras = _ReqExtras()
880
881 # Mapping of requirement to set of distributions that required it;
882 # useful for reporting info about conflicts.
883 required_by: collections.defaultdict[Requirement, set[str]] = (
884 collections.defaultdict(set)
885 )
886
887 while requirements:
888 # process dependencies breadth-first
889 req = requirements.pop(0)
890 if req in processed:
891 # Ignore cyclic or redundant dependencies
892 continue
893
894 if not req_extras.markers_pass(req, extras):
895 continue
896
897 dist = self._resolve_dist(
898 req, best, replace_conflicting, env, installer, required_by, to_activate
899 )
900
901 # push the new requirements onto the stack
902 new_requirements = dist.requires(req.extras)[::-1]
903 requirements.extend(new_requirements)
904
905 # Register the new requirements needed by req
906 for new_requirement in new_requirements:
907 required_by[new_requirement].add(req.project_name)
908 req_extras[new_requirement] = req.extras
909
910 processed.add(req)
911
912 # return list of distros to activate
913 return to_activate
914
915 def _resolve_dist(
916 self, req, best, replace_conflicting, env, installer, required_by, to_activate
917 ) -> Distribution:
918 dist = best.get(req.key)
919 if dist is None:
920 # Find the best distribution and add it to the map
921 dist = self.by_key.get(req.key)
922 if dist is None or (dist not in req and replace_conflicting):
923 ws = self
924 if env is None:
925 if dist is None:
926 env = Environment(self.entries)
927 else:
928 # Use an empty environment and workingset to avoid
929 # any further conflicts with the conflicting
930 # distribution
931 env = Environment([])
932 ws = WorkingSet([])
933 dist = best[req.key] = env.best_match(
934 req, ws, installer, replace_conflicting=replace_conflicting
935 )
936 if dist is None:
937 requirers = required_by.get(req, None)
938 raise DistributionNotFound(req, requirers)
939 to_activate.append(dist)
940 if dist not in req:
941 # Oops, the "best" so far conflicts with a dependency
942 dependent_req = required_by[req]
943 raise VersionConflict(dist, req).with_context(dependent_req)
944 return dist
945
946 @overload
947 def find_plugins(
948 self,
949 plugin_env: Environment,
950 full_env: Environment | None,
951 installer: _StrictInstallerType[_DistributionT],
952 fallback: bool = True,
953 ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...
954 @overload
955 def find_plugins(
956 self,
957 plugin_env: Environment,
958 full_env: Environment | None = None,
959 *,
960 installer: _StrictInstallerType[_DistributionT],
961 fallback: bool = True,
962 ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...
963 @overload
964 def find_plugins(
965 self,
966 plugin_env: Environment,
967 full_env: Environment | None = None,
968 installer: _InstallerType | None = None,
969 fallback: bool = True,
970 ) -> tuple[list[Distribution], dict[Distribution, Exception]]: ...
971 def find_plugins(
972 self,
973 plugin_env: Environment,
974 full_env: Environment | None = None,
975 installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None,
976 fallback: bool = True,
977 ) -> tuple[
978 list[Distribution] | list[_DistributionT],
979 dict[Distribution, Exception],
980 ]:
981 """Find all activatable distributions in `plugin_env`
982
983 Example usage::
984
985 distributions, errors = working_set.find_plugins(
986 Environment(plugin_dirlist)
987 )
988 # add plugins+libs to sys.path
989 map(working_set.add, distributions)
990 # display errors
991 print('Could not load', errors)
992
993 The `plugin_env` should be an ``Environment`` instance that contains
994 only distributions that are in the project's "plugin directory" or
995 directories. The `full_env`, if supplied, should be an ``Environment``
996 contains all currently-available distributions. If `full_env` is not
997 supplied, one is created automatically from the ``WorkingSet`` this
998 method is called on, which will typically mean that every directory on
999 ``sys.path`` will be scanned for distributions.
1000
1001 `installer` is a standard installer callback as used by the
1002 ``resolve()`` method. The `fallback` flag indicates whether we should
1003 attempt to resolve older versions of a plugin if the newest version
1004 cannot be resolved.
1005
1006 This method returns a 2-tuple: (`distributions`, `error_info`), where
1007 `distributions` is a list of the distributions found in `plugin_env`
1008 that were loadable, along with any other distributions that are needed
1009 to resolve their dependencies. `error_info` is a dictionary mapping
1010 unloadable plugin distributions to an exception instance describing the
1011 error that occurred. Usually this will be a ``DistributionNotFound`` or
1012 ``VersionConflict`` instance.
1013 """
1014
1015 plugin_projects = list(plugin_env)
1016 # scan project names in alphabetic order
1017 plugin_projects.sort()
1018
1019 error_info: dict[Distribution, Exception] = {}
1020 distributions: dict[Distribution, Exception | None] = {}
1021
1022 if full_env is None:
1023 env = Environment(self.entries)
1024 env += plugin_env
1025 else:
1026 env = full_env + plugin_env
1027
1028 shadow_set = self.__class__([])
1029 # put all our entries in shadow_set
1030 list(map(shadow_set.add, self))
1031
1032 for project_name in plugin_projects:
1033 for dist in plugin_env[project_name]:
1034 req = [dist.as_requirement()]
1035
1036 try:
1037 resolvees = shadow_set.resolve(req, env, installer)
1038
1039 except ResolutionError as v:
1040 # save error info
1041 error_info[dist] = v
1042 if fallback:
1043 # try the next older version of project
1044 continue
1045 else:
1046 # give up on this project, keep going
1047 break
1048
1049 else:
1050 list(map(shadow_set.add, resolvees))
1051 distributions.update(dict.fromkeys(resolvees))
1052
1053 # success, no need to try any more versions of this project
1054 break
1055
1056 sorted_distributions = list(distributions)
1057 sorted_distributions.sort()
1058
1059 return sorted_distributions, error_info
1060
1061 def require(self, *requirements: _NestedStr) -> list[Distribution]:
1062 """Ensure that distributions matching `requirements` are activated
1063
1064 `requirements` must be a string or a (possibly-nested) sequence
1065 thereof, specifying the distributions and versions required. The
1066 return value is a sequence of the distributions that needed to be
1067 activated to fulfill the requirements; all relevant distributions are
1068 included, even if they were already activated in this working set.
1069 """
1070 needed = self.resolve(parse_requirements(requirements))
1071
1072 for dist in needed:
1073 self.add(dist)
1074
1075 return needed
1076
1077 def subscribe(
1078 self, callback: Callable[[Distribution], object], existing: bool = True
1079 ) -> None:
1080 """Invoke `callback` for all distributions
1081
1082 If `existing=True` (default),
1083 call on all existing ones, as well.
1084 """
1085 if callback in self.callbacks:
1086 return
1087 self.callbacks.append(callback)
1088 if not existing:
1089 return
1090 for dist in self:
1091 callback(dist)
1092
1093 def _added_new(self, dist):
1094 for callback in self.callbacks:
1095 callback(dist)
1096
1097 def __getstate__(
1098 self,
1099 ) -> tuple[
1100 list[str],
1101 dict[str | None, list[str]],
1102 dict[str, Distribution],
1103 dict[str, str],
1104 list[Callable[[Distribution], object]],
1105 ]:
1106 return (
1107 self.entries[:],
1108 self.entry_keys.copy(),
1109 self.by_key.copy(),
1110 self.normalized_to_canonical_keys.copy(),
1111 self.callbacks[:],
1112 )
1113
1114 def __setstate__(self, e_k_b_n_c) -> None:
1115 entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c
1116 self.entries = entries[:]
1117 self.entry_keys = keys.copy()
1118 self.by_key = by_key.copy()
1119 self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy()
1120 self.callbacks = callbacks[:]
1121
1122
1123 class _ReqExtras(Dict["Requirement", Tuple[str, ...]]):
1124 """
1125 Map each requirement to the extras that demanded it.
1126 """
1127
1128 def markers_pass(self, req: Requirement, extras: tuple[str, ...] | None = None):
1129 """
1130 Evaluate markers for req against each extra that
1131 demanded it.
1132
1133 Return False if the req has a marker and fails
1134 evaluation. Otherwise, return True.
1135 """
1136 return not req.marker or any(
1137 req.marker.evaluate({'extra': extra})
1138 for extra in self.get(req, ()) + (extras or ("",))
1139 )
1140
1141
1142 class Environment:
1143 """Searchable snapshot of distributions on a search path"""
1144
1145 def __init__(
1146 self,
1147 search_path: Iterable[str] | None = None,
1148 platform: str | None = get_supported_platform(),
1149 python: str | None = PY_MAJOR,
1150 ) -> None:
1151 """Snapshot distributions available on a search path
1152
1153 Any distributions found on `search_path` are added to the environment.
1154 `search_path` should be a sequence of ``sys.path`` items. If not
1155 supplied, ``sys.path`` is used.
1156
1157 `platform` is an optional string specifying the name of the platform
1158 that platform-specific distributions must be compatible with. If
1159 unspecified, it defaults to the current platform. `python` is an
1160 optional string naming the desired version of Python (e.g. ``'3.6'``);
1161 it defaults to the current version.
1162
1163 You may explicitly set `platform` (and/or `python`) to ``None`` if you
1164 wish to map *all* distributions, not just those compatible with the
1165 running platform or Python version.
1166 """
1167 self._distmap: dict[str, list[Distribution]] = {}
1168 self.platform = platform
1169 self.python = python
1170 self.scan(search_path)
1171
1172 def can_add(self, dist: Distribution) -> bool:
1173 """Is distribution `dist` acceptable for this environment?
1174
1175 The distribution must match the platform and python version
1176 requirements specified when this environment was created, or False
1177 is returned.
1178 """
1179 py_compat = (
1180 self.python is None
1181 or dist.py_version is None
1182 or dist.py_version == self.python
1183 )
1184 return py_compat and compatible_platforms(dist.platform, self.platform)
1185
1186 def remove(self, dist: Distribution) -> None:
1187 """Remove `dist` from the environment"""
1188 self._distmap[dist.key].remove(dist)
1189
1190 def scan(self, search_path: Iterable[str] | None = None) -> None:
1191 """Scan `search_path` for distributions usable in this environment
1192
1193 Any distributions found are added to the environment.
1194 `search_path` should be a sequence of ``sys.path`` items. If not
1195 supplied, ``sys.path`` is used. Only distributions conforming to
1196 the platform/python version defined at initialization are added.
1197 """
1198 if search_path is None:
1199 search_path = sys.path
1200
1201 for item in search_path:
1202 for dist in find_distributions(item):
1203 self.add(dist)
1204
1205 def __getitem__(self, project_name: str) -> list[Distribution]:
1206 """Return a newest-to-oldest list of distributions for `project_name`
1207
1208 Uses case-insensitive `project_name` comparison, assuming all the
1209 project's distributions use their project's name converted to all
1210 lowercase as their key.
1211
1212 """
1213 distribution_key = project_name.lower()
1214 return self._distmap.get(distribution_key, [])
1215
1216 def add(self, dist: Distribution) -> None:
1217 """Add `dist` if we ``can_add()`` it and it has not already been added"""
1218 if self.can_add(dist) and dist.has_version():
1219 dists = self._distmap.setdefault(dist.key, [])
1220 if dist not in dists:
1221 dists.append(dist)
1222 dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
1223
1224 @overload
1225 def best_match(
1226 self,
1227 req: Requirement,
1228 working_set: WorkingSet,
1229 installer: _StrictInstallerType[_DistributionT],
1230 replace_conflicting: bool = False,
1231 ) -> _DistributionT: ...
1232 @overload
1233 def best_match(
1234 self,
1235 req: Requirement,
1236 working_set: WorkingSet,
1237 installer: _InstallerType | None = None,
1238 replace_conflicting: bool = False,
1239 ) -> Distribution | None: ...
1240 def best_match(
1241 self,
1242 req: Requirement,
1243 working_set: WorkingSet,
1244 installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None,
1245 replace_conflicting: bool = False,
1246 ) -> Distribution | None:
1247 """Find distribution best matching `req` and usable on `working_set`
1248
1249 This calls the ``find(req)`` method of the `working_set` to see if a
1250 suitable distribution is already active. (This may raise
1251 ``VersionConflict`` if an unsuitable version of the project is already
1252 active in the specified `working_set`.) If a suitable distribution
1253 isn't active, this method returns the newest distribution in the
1254 environment that meets the ``Requirement`` in `req`. If no suitable
1255 distribution is found, and `installer` is supplied, then the result of
1256 calling the environment's ``obtain(req, installer)`` method will be
1257 returned.
1258 """
1259 try:
1260 dist = working_set.find(req)
1261 except VersionConflict:
1262 if not replace_conflicting:
1263 raise
1264 dist = None
1265 if dist is not None:
1266 return dist
1267 for dist in self[req.key]:
1268 if dist in req:
1269 return dist
1270 # try to download/install
1271 return self.obtain(req, installer)
1272
1273 @overload
1274 def obtain(
1275 self,
1276 requirement: Requirement,
1277 installer: _StrictInstallerType[_DistributionT],
1278 ) -> _DistributionT: ...
1279 @overload
1280 def obtain(
1281 self,
1282 requirement: Requirement,
1283 installer: Callable[[Requirement], None] | None = None,
1284 ) -> None: ...
1285 @overload
1286 def obtain(
1287 self,
1288 requirement: Requirement,
1289 installer: _InstallerType | None = None,
1290 ) -> Distribution | None: ...
1291 def obtain(
1292 self,
1293 requirement: Requirement,
1294 installer: Callable[[Requirement], None]
1295 | _InstallerType
1296 | None
1297 | _StrictInstallerType[_DistributionT] = None,
1298 ) -> Distribution | None:
1299 """Obtain a distribution matching `requirement` (e.g. via download)
1300
1301 Obtain a distro that matches requirement (e.g. via download). In the
1302 base ``Environment`` class, this routine just returns
1303 ``installer(requirement)``, unless `installer` is None, in which case
1304 None is returned instead. This method is a hook that allows subclasses
1305 to attempt other ways of obtaining a distribution before falling back
1306 to the `installer` argument."""
1307 return installer(requirement) if installer else None
1308
1309 def __iter__(self) -> Iterator[str]:
1310 """Yield the unique project names of the available distributions"""
1311 for key in self._distmap.keys():
1312 if self[key]:
1313 yield key
1314
1315 def __iadd__(self, other: Distribution | Environment) -> Self:
1316 """In-place addition of a distribution or environment"""
1317 if isinstance(other, Distribution):
1318 self.add(other)
1319 elif isinstance(other, Environment):
1320 for project in other:
1321 for dist in other[project]:
1322 self.add(dist)
1323 else:
1324 raise TypeError("Can't add %r to environment" % (other,))
1325 return self
1326
1327 def __add__(self, other: Distribution | Environment) -> Self:
1328 """Add an environment or distribution to an environment"""
1329 new = self.__class__([], platform=None, python=None)
1330 for env in self, other:
1331 new += env
1332 return new
1333
1334
1335 # XXX backward compatibility
1336 AvailableDistributions = Environment
1337
1338
1339 class ExtractionError(RuntimeError):
1340 """An error occurred extracting a resource
1341
1342 The following attributes are available from instances of this exception:
1343
1344 manager
1345 The resource manager that raised this exception
1346
1347 cache_path
1348 The base directory for resource extraction
1349
1350 original_error
1351 The exception instance that caused extraction to fail
1352 """
1353
1354 manager: ResourceManager
1355 cache_path: str
1356 original_error: BaseException | None
1357
1358
1359 class ResourceManager:
1360 """Manage resource extraction and packages"""
1361
1362 extraction_path: str | None = None
1363
1364 def __init__(self) -> None:
1365 # acts like a set
1366 self.cached_files: dict[str, Literal[True]] = {}
1367
1368 def resource_exists(
1369 self, package_or_requirement: _PkgReqType, resource_name: str
1370 ) -> bool:
1371 """Does the named resource exist?"""
1372 return get_provider(package_or_requirement).has_resource(resource_name)
1373
1374 def resource_isdir(
1375 self, package_or_requirement: _PkgReqType, resource_name: str
1376 ) -> bool:
1377 """Is the named resource an existing directory?"""
1378 return get_provider(package_or_requirement).resource_isdir(resource_name)
1379
1380 def resource_filename(
1381 self, package_or_requirement: _PkgReqType, resource_name: str
1382 ) -> str:
1383 """Return a true filesystem path for specified resource"""
1384 return get_provider(package_or_requirement).get_resource_filename(
1385 self, resource_name
1386 )
1387
1388 def resource_stream(
1389 self, package_or_requirement: _PkgReqType, resource_name: str
1390 ) -> _ResourceStream:
1391 """Return a readable file-like object for specified resource"""
1392 return get_provider(package_or_requirement).get_resource_stream(
1393 self, resource_name
1394 )
1395
1396 def resource_string(
1397 self, package_or_requirement: _PkgReqType, resource_name: str
1398 ) -> bytes:
1399 """Return specified resource as :obj:`bytes`"""
1400 return get_provider(package_or_requirement).get_resource_string(
1401 self, resource_name
1402 )
1403
1404 def resource_listdir(
1405 self, package_or_requirement: _PkgReqType, resource_name: str
1406 ) -> list[str]:
1407 """List the contents of the named resource directory"""
1408 return get_provider(package_or_requirement).resource_listdir(resource_name)
1409
1410 def extraction_error(self) -> NoReturn:
1411 """Give an error message for problems extracting file(s)"""
1412
1413 old_exc = sys.exc_info()[1]
1414 cache_path = self.extraction_path or get_default_cache()
1415
1416 tmpl = textwrap.dedent(
1417 """
1418 Can't extract file(s) to egg cache
1419
1420 The following error occurred while trying to extract file(s)
1421 to the Python egg cache:
1422
1423 {old_exc}
1424
1425 The Python egg cache directory is currently set to:
1426
1427 {cache_path}
1428
1429 Perhaps your account does not have write access to this directory?
1430 You can change the cache directory by setting the PYTHON_EGG_CACHE
1431 environment variable to point to an accessible directory.
1432 """
1433 ).lstrip()
1434 err = ExtractionError(tmpl.format(**locals()))
1435 err.manager = self
1436 err.cache_path = cache_path
1437 err.original_error = old_exc
1438 raise err
1439
1440 def get_cache_path(self, archive_name: str, names: Iterable[StrPath] = ()) -> str:
1441 """Return absolute location in cache for `archive_name` and `names`
1442
1443 The parent directory of the resulting path will be created if it does
1444 not already exist. `archive_name` should be the base filename of the
1445 enclosing egg (which may not be the name of the enclosing zipfile!),
1446 including its ".egg" extension. `names`, if provided, should be a
1447 sequence of path name parts "under" the egg's extraction location.
1448
1449 This method should only be called by resource providers that need to
1450 obtain an extraction location, and only for names they intend to
1451 extract, as it tracks the generated names for possible cleanup later.
1452 """
1453 extract_path = self.extraction_path or get_default_cache()
1454 target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
1455 try:
1456 _bypass_ensure_directory(target_path)
1457 except Exception:
1458 self.extraction_error()
1459
1460 self._warn_unsafe_extraction_path(extract_path)
1461
1462 self.cached_files[target_path] = True
1463 return target_path
1464
1465 @staticmethod
1466 def _warn_unsafe_extraction_path(path):
1467 """
1468 If the default extraction path is overridden and set to an insecure
1469 location, such as /tmp, it opens up an opportunity for an attacker to
1470 replace an extracted file with an unauthorized payload. Warn the user
1471 if a known insecure location is used.
1472
1473 See Distribute #375 for more details.
1474 """
1475 if os.name == 'nt' and not path.startswith(os.environ['windir']):
1476 # On Windows, permissions are generally restrictive by default
1477 # and temp directories are not writable by other users, so
1478 # bypass the warning.
1479 return
1480 mode = os.stat(path).st_mode
1481 if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
1482 msg = (
1483 "Extraction path is writable by group/others "
1484 "and vulnerable to attack when "
1485 "used with get_resource_filename ({path}). "
1486 "Consider a more secure "
1487 "location (set with .set_extraction_path or the "
1488 "PYTHON_EGG_CACHE environment variable)."
1489 ).format(**locals())
1490 warnings.warn(msg, UserWarning)
1491
1492 def postprocess(self, tempname: StrOrBytesPath, filename: StrOrBytesPath) -> None:
1493 """Perform any platform-specific postprocessing of `tempname`
1494
1495 This is where Mac header rewrites should be done; other platforms don't
1496 have anything special they should do.
1497
1498 Resource providers should call this method ONLY after successfully
1499 extracting a compressed resource. They must NOT call it on resources
1500 that are already in the filesystem.
1501
1502 `tempname` is the current (temporary) name of the file, and `filename`
1503 is the name it will be renamed to by the caller after this routine
1504 returns.
1505 """
1506
1507 if os.name == 'posix':
1508 # Make the resource executable
1509 mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
1510 os.chmod(tempname, mode)
1511
1512 def set_extraction_path(self, path: str) -> None:
1513 """Set the base path where resources will be extracted to, if needed.
1514
1515 If you do not call this routine before any extractions take place, the
1516 path defaults to the return value of ``get_default_cache()``. (Which
1517 is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
1518 platform-specific fallbacks. See that routine's documentation for more
1519 details.)
1520
1521 Resources are extracted to subdirectories of this path based upon
1522 information given by the ``IResourceProvider``. You may set this to a
1523 temporary directory, but then you must call ``cleanup_resources()`` to
1524 delete the extracted files when done. There is no guarantee that
1525 ``cleanup_resources()`` will be able to remove all extracted files.
1526
1527 (Note: you may not change the extraction path for a given resource
1528 manager once resources have been extracted, unless you first call
1529 ``cleanup_resources()``.)
1530 """
1531 if self.cached_files:
1532 raise ValueError("Can't change extraction path, files already extracted")
1533
1534 self.extraction_path = path
1535
1536 def cleanup_resources(self, force: bool = False) -> list[str]:
1537 """
1538 Delete all extracted resource files and directories, returning a list
1539 of the file and directory names that could not be successfully removed.
1540 This function does not have any concurrency protection, so it should
1541 generally only be called when the extraction path is a temporary
1542 directory exclusive to a single process. This method is not
1543 automatically called; you must call it explicitly or register it as an
1544 ``atexit`` function if you wish to ensure cleanup of a temporary
1545 directory used for extractions.
1546 """
1547 # XXX
1548 return []
1549
1550
1551 def get_default_cache() -> str:
1552 """
1553 Return the ``PYTHON_EGG_CACHE`` environment variable
1554 or a platform-relevant user cache dir for an app
1555 named "Python-Eggs".
1556 """
1557 return os.environ.get('PYTHON_EGG_CACHE') or _user_cache_dir(appname='Python-Eggs')
1558
1559
1560 def safe_name(name: str) -> str:
1561 """Convert an arbitrary string to a standard distribution name
1562
1563 Any runs of non-alphanumeric/. characters are replaced with a single '-'.
1564 """
1565 return re.sub('[^A-Za-z0-9.]+', '-', name)
1566
1567
1568 def safe_version(version: str) -> str:
1569 """
1570 Convert an arbitrary string to a standard version string
1571 """
1572 try:
1573 # normalize the version
1574 return str(packaging.version.Version(version))
1575 except packaging.version.InvalidVersion:
1576 version = version.replace(' ', '.')
1577 return re.sub('[^A-Za-z0-9.]+', '-', version)
1578
1579
1580 def _forgiving_version(version):
1581 """Fallback when ``safe_version`` is not safe enough
1582 >>> parse_version(_forgiving_version('0.23ubuntu1'))
1583 <Version('0.23.dev0+sanitized.ubuntu1')>
1584 >>> parse_version(_forgiving_version('0.23-'))
1585 <Version('0.23.dev0+sanitized')>
1586 >>> parse_version(_forgiving_version('0.-_'))
1587 <Version('0.dev0+sanitized')>
1588 >>> parse_version(_forgiving_version('42.+?1'))
1589 <Version('42.dev0+sanitized.1')>
1590 >>> parse_version(_forgiving_version('hello world'))
1591 <Version('0.dev0+sanitized.hello.world')>
1592 """
1593 version = version.replace(' ', '.')
1594 match = _PEP440_FALLBACK.search(version)
1595 if match:
1596 safe = match["safe"]
1597 rest = version[len(safe) :]
1598 else:
1599 safe = "0"
1600 rest = version
1601 local = f"sanitized.{_safe_segment(rest)}".strip(".")
1602 return f"{safe}.dev0+{local}"
1603
1604
1605 def _safe_segment(segment):
1606 """Convert an arbitrary string into a safe segment"""
1607 segment = re.sub('[^A-Za-z0-9.]+', '-', segment)
1608 segment = re.sub('-[^A-Za-z0-9]+', '-', segment)
1609 return re.sub(r'\.[^A-Za-z0-9]+', '.', segment).strip(".-")
1610
1611
1612 def safe_extra(extra: str) -> str:
1613 """Convert an arbitrary string to a standard 'extra' name
1614
1615 Any runs of non-alphanumeric characters are replaced with a single '_',
1616 and the result is always lowercased.
1617 """
1618 return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
1619
1620
1621 def to_filename(name: str) -> str:
1622 """Convert a project or version name to its filename-escaped form
1623
1624 Any '-' characters are currently replaced with '_'.
1625 """
1626 return name.replace('-', '_')
1627
1628
1629 def invalid_marker(text: str) -> SyntaxError | Literal[False]:
1630 """
1631 Validate text as a PEP 508 environment marker; return an exception
1632 if invalid or False otherwise.
1633 """
1634 try:
1635 evaluate_marker(text)
1636 except SyntaxError as e:
1637 e.filename = None
1638 e.lineno = None
1639 return e
1640 return False
1641
1642
1643 def evaluate_marker(text: str, extra: str | None = None) -> bool:
1644 """
1645 Evaluate a PEP 508 environment marker.
1646 Return a boolean indicating the marker result in this environment.
1647 Raise SyntaxError if marker is invalid.
1648
1649 This implementation uses the 'pyparsing' module.
1650 """
1651 try:
1652 marker = packaging.markers.Marker(text)
1653 return marker.evaluate()
1654 except packaging.markers.InvalidMarker as e:
1655 raise SyntaxError(e) from e
1656
1657
1658 class NullProvider:
1659 """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
1660
1661 egg_name: str | None = None
1662 egg_info: str | None = None
1663 loader: LoaderProtocol | None = None
1664
1665 def __init__(self, module: _ModuleLike) -> None:
1666 self.loader = getattr(module, '__loader__', None)
1667 self.module_path = os.path.dirname(getattr(module, '__file__', ''))
1668
1669 def get_resource_filename(
1670 self, manager: ResourceManager, resource_name: str
1671 ) -> str:
1672 return self._fn(self.module_path, resource_name)
1673
1674 def get_resource_stream(
1675 self, manager: ResourceManager, resource_name: str
1676 ) -> BinaryIO:
1677 return io.BytesIO(self.get_resource_string(manager, resource_name))
1678
1679 def get_resource_string(
1680 self, manager: ResourceManager, resource_name: str
1681 ) -> bytes:
1682 return self._get(self._fn(self.module_path, resource_name))
1683
1684 def has_resource(self, resource_name: str) -> bool:
1685 return self._has(self._fn(self.module_path, resource_name))
1686
1687 def _get_metadata_path(self, name):
1688 return self._fn(self.egg_info, name)
1689
1690 def has_metadata(self, name: str) -> bool:
1691 if not self.egg_info:
1692 return False
1693
1694 path = self._get_metadata_path(name)
1695 return self._has(path)
1696
1697 def get_metadata(self, name: str) -> str:
1698 if not self.egg_info:
1699 return ""
1700 path = self._get_metadata_path(name)
1701 value = self._get(path)
1702 try:
1703 return value.decode('utf-8')
1704 except UnicodeDecodeError as exc:
1705 # Include the path in the error message to simplify
1706 # troubleshooting, and without changing the exception type.
1707 exc.reason += ' in {} file at path: {}'.format(name, path)
1708 raise
1709
1710 def get_metadata_lines(self, name: str) -> Iterator[str]:
1711 return yield_lines(self.get_metadata(name))
1712
1713 def resource_isdir(self, resource_name: str) -> bool:
1714 return self._isdir(self._fn(self.module_path, resource_name))
1715
1716 def metadata_isdir(self, name: str) -> bool:
1717 return bool(self.egg_info and self._isdir(self._fn(self.egg_info, name)))
1718
1719 def resource_listdir(self, resource_name: str) -> list[str]:
1720 return self._listdir(self._fn(self.module_path, resource_name))
1721
1722 def metadata_listdir(self, name: str) -> list[str]:
1723 if self.egg_info:
1724 return self._listdir(self._fn(self.egg_info, name))
1725 return []
1726
1727 def run_script(self, script_name: str, namespace: dict[str, Any]) -> None:
1728 script = 'scripts/' + script_name
1729 if not self.has_metadata(script):
1730 raise ResolutionError(
1731 "Script {script!r} not found in metadata at {self.egg_info!r}".format(
1732 **locals()
1733 ),
1734 )
1735
1736 script_text = self.get_metadata(script).replace('\r\n', '\n')
1737 script_text = script_text.replace('\r', '\n')
1738 script_filename = self._fn(self.egg_info, script)
1739 namespace['__file__'] = script_filename
1740 if os.path.exists(script_filename):
1741 source = _read_utf8_with_fallback(script_filename)
1742 code = compile(source, script_filename, 'exec')
1743 exec(code, namespace, namespace)
1744 else:
1745 from linecache import cache
1746
1747 cache[script_filename] = (
1748 len(script_text),
1749 0,
1750 script_text.split('\n'),
1751 script_filename,
1752 )
1753 script_code = compile(script_text, script_filename, 'exec')
1754 exec(script_code, namespace, namespace)
1755
1756 def _has(self, path) -> bool:
1757 raise NotImplementedError(
1758 "Can't perform this operation for unregistered loader type"
1759 )
1760
1761 def _isdir(self, path) -> bool:
1762 raise NotImplementedError(
1763 "Can't perform this operation for unregistered loader type"
1764 )
1765
1766 def _listdir(self, path) -> list[str]:
1767 raise NotImplementedError(
1768 "Can't perform this operation for unregistered loader type"
1769 )
1770
1771 def _fn(self, base: str | None, resource_name: str):
1772 if base is None:
1773 raise TypeError(
1774 "`base` parameter in `_fn` is `None`. Either override this method or check the parameter first."
1775 )
1776 self._validate_resource_path(resource_name)
1777 if resource_name:
1778 return os.path.join(base, *resource_name.split('/'))
1779 return base
1780
1781 @staticmethod
1782 def _validate_resource_path(path):
1783 """
1784 Validate the resource paths according to the docs.
1785 https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access
1786
1787 >>> warned = getfixture('recwarn')
1788 >>> warnings.simplefilter('always')
1789 >>> vrp = NullProvider._validate_resource_path
1790 >>> vrp('foo/bar.txt')
1791 >>> bool(warned)
1792 False
1793 >>> vrp('../foo/bar.txt')
1794 >>> bool(warned)
1795 True
1796 >>> warned.clear()
1797 >>> vrp('/foo/bar.txt')
1798 >>> bool(warned)
1799 True
1800 >>> vrp('foo/../../bar.txt')
1801 >>> bool(warned)
1802 True
1803 >>> warned.clear()
1804 >>> vrp('foo/f../bar.txt')
1805 >>> bool(warned)
1806 False
1807
1808 Windows path separators are straight-up disallowed.
1809 >>> vrp(r'\\foo/bar.txt')
1810 Traceback (most recent call last):
1811 ...
1812 ValueError: Use of .. or absolute path in a resource path \
1813 is not allowed.
1814
1815 >>> vrp(r'C:\\foo/bar.txt')
1816 Traceback (most recent call last):
1817 ...
1818 ValueError: Use of .. or absolute path in a resource path \
1819 is not allowed.
1820
1821 Blank values are allowed
1822
1823 >>> vrp('')
1824 >>> bool(warned)
1825 False
1826
1827 Non-string values are not.
1828
1829 >>> vrp(None)
1830 Traceback (most recent call last):
1831 ...
1832 AttributeError: ...
1833 """
1834 invalid = (
1835 os.path.pardir in path.split(posixpath.sep)
1836 or posixpath.isabs(path)
1837 or ntpath.isabs(path)
1838 or path.startswith("\\")
1839 )
1840 if not invalid:
1841 return
1842
1843 msg = "Use of .. or absolute path in a resource path is not allowed."
1844
1845 # Aggressively disallow Windows absolute paths
1846 if (path.startswith("\\") or ntpath.isabs(path)) and not posixpath.isabs(path):
1847 raise ValueError(msg)
1848
1849 # for compatibility, warn; in future
1850 # raise ValueError(msg)
1851 issue_warning(
1852 msg[:-1] + " and will raise exceptions in a future release.",
1853 DeprecationWarning,
1854 )
1855
1856 def _get(self, path) -> bytes:
1857 if hasattr(self.loader, 'get_data') and self.loader:
1858 # Already checked get_data exists
1859 return self.loader.get_data(path) # type: ignore[attr-defined]
1860 raise NotImplementedError(
1861 "Can't perform this operation for loaders without 'get_data()'"
1862 )
1863
1864
1865 register_loader_type(object, NullProvider)
1866
1867
1868 def _parents(path):
1869 """
1870 yield all parents of path including path
1871 """
1872 last = None
1873 while path != last:
1874 yield path
1875 last = path
1876 path, _ = os.path.split(path)
1877
1878
1879 class EggProvider(NullProvider):
1880 """Provider based on a virtual filesystem"""
1881
1882 def __init__(self, module: _ModuleLike) -> None:
1883 super().__init__(module)
1884 self._setup_prefix()
1885
1886 def _setup_prefix(self):
1887 # Assume that metadata may be nested inside a "basket"
1888 # of multiple eggs and use module_path instead of .archive.
1889 eggs = filter(_is_egg_path, _parents(self.module_path))
1890 egg = next(eggs, None)
1891 egg and self._set_egg(egg)
1892
1893 def _set_egg(self, path: str):
1894 self.egg_name = os.path.basename(path)
1895 self.egg_info = os.path.join(path, 'EGG-INFO')
1896 self.egg_root = path
1897
1898
1899 class DefaultProvider(EggProvider):
1900 """Provides access to package resources in the filesystem"""
1901
1902 def _has(self, path) -> bool:
1903 return os.path.exists(path)
1904
1905 def _isdir(self, path) -> bool:
1906 return os.path.isdir(path)
1907
1908 def _listdir(self, path):
1909 return os.listdir(path)
1910
1911 def get_resource_stream(
1912 self, manager: object, resource_name: str
1913 ) -> io.BufferedReader:
1914 return open(self._fn(self.module_path, resource_name), 'rb')
1915
1916 def _get(self, path) -> bytes:
1917 with open(path, 'rb') as stream:
1918 return stream.read()
1919
1920 @classmethod
1921 def _register(cls):
1922 loader_names = (
1923 'SourceFileLoader',
1924 'SourcelessFileLoader',
1925 )
1926 for name in loader_names:
1927 loader_cls = getattr(importlib.machinery, name, type(None))
1928 register_loader_type(loader_cls, cls)
1929
1930
1931 DefaultProvider._register()
1932
1933
1934 class EmptyProvider(NullProvider):
1935 """Provider that returns nothing for all requests"""
1936
1937 # A special case, we don't want all Providers inheriting from NullProvider to have a potentially None module_path
1938 module_path: str | None = None # type: ignore[assignment]
1939
1940 _isdir = _has = lambda self, path: False
1941
1942 def _get(self, path) -> bytes:
1943 return b''
1944
1945 def _listdir(self, path):
1946 return []
1947
1948 def __init__(self) -> None:
1949 pass
1950
1951
1952 empty_provider = EmptyProvider()
1953
1954
1955 class ZipManifests(Dict[str, "MemoizedZipManifests.manifest_mod"]):
1956 """
1957 zip manifest builder
1958 """
1959
1960 # `path` could be `StrPath | IO[bytes]` but that violates the LSP for `MemoizedZipManifests.load`
1961 @classmethod
1962 def build(cls, path: str) -> dict[str, zipfile.ZipInfo]:
1963 """
1964 Build a dictionary similar to the zipimport directory
1965 caches, except instead of tuples, store ZipInfo objects.
1966
1967 Use a platform-specific path separator (os.sep) for the path keys
1968 for compatibility with pypy on Windows.
1969 """
1970 with zipfile.ZipFile(path) as zfile:
1971 items = (
1972 (
1973 name.replace('/', os.sep),
1974 zfile.getinfo(name),
1975 )
1976 for name in zfile.namelist()
1977 )
1978 return dict(items)
1979
1980 load = build
1981
1982
1983 class MemoizedZipManifests(ZipManifests):
1984 """
1985 Memoized zipfile manifests.
1986 """
1987
1988 class manifest_mod(NamedTuple):
1989 manifest: dict[str, zipfile.ZipInfo]
1990 mtime: float
1991
1992 def load(self, path: str) -> dict[str, zipfile.ZipInfo]: # type: ignore[override] # ZipManifests.load is a classmethod
1993 """
1994 Load a manifest at path or return a suitable manifest already loaded.
1995 """
1996 path = os.path.normpath(path)
1997 mtime = os.stat(path).st_mtime
1998
1999 if path not in self or self[path].mtime != mtime:
2000 manifest = self.build(path)
2001 self[path] = self.manifest_mod(manifest, mtime)
2002
2003 return self[path].manifest
2004
2005
2006 class ZipProvider(EggProvider):
2007 """Resource support for zips and eggs"""
2008
2009 eagers: list[str] | None = None
2010 _zip_manifests = MemoizedZipManifests()
2011 # ZipProvider's loader should always be a zipimporter or equivalent
2012 loader: zipimport.zipimporter
2013
2014 def __init__(self, module: _ZipLoaderModule) -> None:
2015 super().__init__(module)
2016 self.zip_pre = self.loader.archive + os.sep
2017
2018 def _zipinfo_name(self, fspath):
2019 # Convert a virtual filename (full path to file) into a zipfile subpath
2020 # usable with the zipimport directory cache for our target archive
2021 fspath = fspath.rstrip(os.sep)
2022 if fspath == self.loader.archive:
2023 return ''
2024 if fspath.startswith(self.zip_pre):
2025 return fspath[len(self.zip_pre) :]
2026 raise AssertionError("%s is not a subpath of %s" % (fspath, self.zip_pre))
2027
2028 def _parts(self, zip_path):
2029 # Convert a zipfile subpath into an egg-relative path part list.
2030 # pseudo-fs path
2031 fspath = self.zip_pre + zip_path
2032 if fspath.startswith(self.egg_root + os.sep):
2033 return fspath[len(self.egg_root) + 1 :].split(os.sep)
2034 raise AssertionError("%s is not a subpath of %s" % (fspath, self.egg_root))
2035
2036 @property
2037 def zipinfo(self):
2038 return self._zip_manifests.load(self.loader.archive)
2039
2040 def get_resource_filename(
2041 self, manager: ResourceManager, resource_name: str
2042 ) -> str:
2043 if not self.egg_name:
2044 raise NotImplementedError(
2045 "resource_filename() only supported for .egg, not .zip"
2046 )
2047 # no need to lock for extraction, since we use temp names
2048 zip_path = self._resource_to_zip(resource_name)
2049 eagers = self._get_eager_resources()
2050 if '/'.join(self._parts(zip_path)) in eagers:
2051 for name in eagers:
2052 self._extract_resource(manager, self._eager_to_zip(name))
2053 return self._extract_resource(manager, zip_path)
2054
2055 @staticmethod
2056 def _get_date_and_size(zip_stat):
2057 size = zip_stat.file_size
2058 # ymdhms+wday, yday, dst
2059 date_time = zip_stat.date_time + (0, 0, -1)
2060 # 1980 offset already done
2061 timestamp = time.mktime(date_time)
2062 return timestamp, size
2063
2064 # FIXME: 'ZipProvider._extract_resource' is too complex (12)
2065 def _extract_resource(self, manager: ResourceManager, zip_path) -> str: # noqa: C901
2066 if zip_path in self._index():
2067 for name in self._index()[zip_path]:
2068 last = self._extract_resource(manager, os.path.join(zip_path, name))
2069 # return the extracted directory name
2070 return os.path.dirname(last)
2071
2072 timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
2073
2074 if not WRITE_SUPPORT:
2075 raise OSError(
2076 '"os.rename" and "os.unlink" are not supported on this platform'
2077 )
2078 try:
2079 if not self.egg_name:
2080 raise OSError(
2081 '"egg_name" is empty. This likely means no egg could be found from the "module_path".'
2082 )
2083 real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path))
2084
2085 if self._is_current(real_path, zip_path):
2086 return real_path
2087
2088 outf, tmpnam = _mkstemp(
2089 ".$extract",
2090 dir=os.path.dirname(real_path),
2091 )
2092 os.write(outf, self.loader.get_data(zip_path))
2093 os.close(outf)
2094 utime(tmpnam, (timestamp, timestamp))
2095 manager.postprocess(tmpnam, real_path)
2096
2097 try:
2098 rename(tmpnam, real_path)
2099
2100 except OSError:
2101 if os.path.isfile(real_path):
2102 if self._is_current(real_path, zip_path):
2103 # the file became current since it was checked above,
2104 # so proceed.
2105 return real_path
2106 # Windows, del old file and retry
2107 elif os.name == 'nt':
2108 unlink(real_path)
2109 rename(tmpnam, real_path)
2110 return real_path
2111 raise
2112
2113 except OSError:
2114 # report a user-friendly error
2115 manager.extraction_error()
2116
2117 return real_path
2118
2119 def _is_current(self, file_path, zip_path):
2120 """
2121 Return True if the file_path is current for this zip_path
2122 """
2123 timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
2124 if not os.path.isfile(file_path):
2125 return False
2126 stat = os.stat(file_path)
2127 if stat.st_size != size or stat.st_mtime != timestamp:
2128 return False
2129 # check that the contents match
2130 zip_contents = self.loader.get_data(zip_path)
2131 with open(file_path, 'rb') as f:
2132 file_contents = f.read()
2133 return zip_contents == file_contents
2134
2135 def _get_eager_resources(self):
2136 if self.eagers is None:
2137 eagers = []
2138 for name in ('native_libs.txt', 'eager_resources.txt'):
2139 if self.has_metadata(name):
2140 eagers.extend(self.get_metadata_lines(name))
2141 self.eagers = eagers
2142 return self.eagers
2143
2144 def _index(self):
2145 try:
2146 return self._dirindex
2147 except AttributeError:
2148 ind = {}
2149 for path in self.zipinfo:
2150 parts = path.split(os.sep)
2151 while parts:
2152 parent = os.sep.join(parts[:-1])
2153 if parent in ind:
2154 ind[parent].append(parts[-1])
2155 break
2156 else:
2157 ind[parent] = [parts.pop()]
2158 self._dirindex = ind
2159 return ind
2160
2161 def _has(self, fspath) -> bool:
2162 zip_path = self._zipinfo_name(fspath)
2163 return zip_path in self.zipinfo or zip_path in self._index()
2164
2165 def _isdir(self, fspath) -> bool:
2166 return self._zipinfo_name(fspath) in self._index()
2167
2168 def _listdir(self, fspath):
2169 return list(self._index().get(self._zipinfo_name(fspath), ()))
2170
2171 def _eager_to_zip(self, resource_name: str):
2172 return self._zipinfo_name(self._fn(self.egg_root, resource_name))
2173
2174 def _resource_to_zip(self, resource_name: str):
2175 return self._zipinfo_name(self._fn(self.module_path, resource_name))
2176
2177
2178 register_loader_type(zipimport.zipimporter, ZipProvider)
2179
2180
2181 class FileMetadata(EmptyProvider):
2182 """Metadata handler for standalone PKG-INFO files
2183
2184 Usage::
2185
2186 metadata = FileMetadata("/path/to/PKG-INFO")
2187
2188 This provider rejects all data and metadata requests except for PKG-INFO,
2189 which is treated as existing, and will be the contents of the file at
2190 the provided location.
2191 """
2192
2193 def __init__(self, path: StrPath) -> None:
2194 self.path = path
2195
2196 def _get_metadata_path(self, name):
2197 return self.path
2198
2199 def has_metadata(self, name: str) -> bool:
2200 return name == 'PKG-INFO' and os.path.isfile(self.path)
2201
2202 def get_metadata(self, name: str) -> str:
2203 if name != 'PKG-INFO':
2204 raise KeyError("No metadata except PKG-INFO is available")
2205
2206 with open(self.path, encoding='utf-8', errors="replace") as f:
2207 metadata = f.read()
2208 self._warn_on_replacement(metadata)
2209 return metadata
2210
2211 def _warn_on_replacement(self, metadata):
2212 replacement_char = '�'
2213 if replacement_char in metadata:
2214 tmpl = "{self.path} could not be properly decoded in UTF-8"
2215 msg = tmpl.format(**locals())
2216 warnings.warn(msg)
2217
2218 def get_metadata_lines(self, name: str) -> Iterator[str]:
2219 return yield_lines(self.get_metadata(name))
2220
2221
2222 class PathMetadata(DefaultProvider):
2223 """Metadata provider for egg directories
2224
2225 Usage::
2226
2227 # Development eggs:
2228
2229 egg_info = "/path/to/PackageName.egg-info"
2230 base_dir = os.path.dirname(egg_info)
2231 metadata = PathMetadata(base_dir, egg_info)
2232 dist_name = os.path.splitext(os.path.basename(egg_info))[0]
2233 dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
2234
2235 # Unpacked egg directories:
2236
2237 egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
2238 metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
2239 dist = Distribution.from_filename(egg_path, metadata=metadata)
2240 """
2241
2242 def __init__(self, path: str, egg_info: str) -> None:
2243 self.module_path = path
2244 self.egg_info = egg_info
2245
2246
2247 class EggMetadata(ZipProvider):
2248 """Metadata provider for .egg files"""
2249
2250 def __init__(self, importer: zipimport.zipimporter) -> None:
2251 """Create a metadata provider from a zipimporter"""
2252
2253 self.zip_pre = importer.archive + os.sep
2254 self.loader = importer
2255 if importer.prefix:
2256 self.module_path = os.path.join(importer.archive, importer.prefix)
2257 else:
2258 self.module_path = importer.archive
2259 self._setup_prefix()
2260
2261
2262 _distribution_finders: dict[type, _DistFinderType[Any]] = _declare_state(
2263 'dict', '_distribution_finders', {}
2264 )
2265
2266
2267 def register_finder(
2268 importer_type: type[_T], distribution_finder: _DistFinderType[_T]
2269 ) -> None:
2270 """Register `distribution_finder` to find distributions in sys.path items
2271
2272 `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
2273 handler), and `distribution_finder` is a callable that, passed a path
2274 item and the importer instance, yields ``Distribution`` instances found on
2275 that path item. See ``pkg_resources.find_on_path`` for an example."""
2276 _distribution_finders[importer_type] = distribution_finder
2277
2278
2279 def find_distributions(path_item: str, only: bool = False) -> Iterable[Distribution]:
2280 """Yield distributions accessible via `path_item`"""
2281 importer = get_importer(path_item)
2282 finder = _find_adapter(_distribution_finders, importer)
2283 return finder(importer, path_item, only)
2284
2285
2286 def find_eggs_in_zip(
2287 importer: zipimport.zipimporter, path_item: str, only: bool = False
2288 ) -> Iterator[Distribution]:
2289 """
2290 Find eggs in zip files; possibly multiple nested eggs.
2291 """
2292 if importer.archive.endswith('.whl'):
2293 # wheels are not supported with this finder
2294 # they don't have PKG-INFO metadata, and won't ever contain eggs
2295 return
2296 metadata = EggMetadata(importer)
2297 if metadata.has_metadata('PKG-INFO'):
2298 yield Distribution.from_filename(path_item, metadata=metadata)
2299 if only:
2300 # don't yield nested distros
2301 return
2302 for subitem in metadata.resource_listdir(''):
2303 if _is_egg_path(subitem):
2304 subpath = os.path.join(path_item, subitem)
2305 dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
2306 yield from dists
2307 elif subitem.lower().endswith(('.dist-info', '.egg-info')):
2308 subpath = os.path.join(path_item, subitem)
2309 submeta = EggMetadata(zipimport.zipimporter(subpath))
2310 submeta.egg_info = subpath
2311 yield Distribution.from_location(path_item, subitem, submeta)
2312
2313
2314 register_finder(zipimport.zipimporter, find_eggs_in_zip)
2315
2316
2317 def find_nothing(
2318 importer: object | None, path_item: str | None, only: bool | None = False
2319 ):
2320 return ()
2321
2322
2323 register_finder(object, find_nothing)
2324
2325
2326 def find_on_path(importer: object | None, path_item, only=False):
2327 """Yield distributions accessible on a sys.path directory"""
2328 path_item = _normalize_cached(path_item)
2329
2330 if _is_unpacked_egg(path_item):
2331 yield Distribution.from_filename(
2332 path_item,
2333 metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')),
2334 )
2335 return
2336
2337 entries = (os.path.join(path_item, child) for child in safe_listdir(path_item))
2338
2339 # scan for .egg and .egg-info in directory
2340 for entry in sorted(entries):
2341 fullpath = os.path.join(path_item, entry)
2342 factory = dist_factory(path_item, entry, only)
2343 yield from factory(fullpath)
2344
2345
2346 def dist_factory(path_item, entry, only):
2347 """Return a dist_factory for the given entry."""
2348 lower = entry.lower()
2349 is_egg_info = lower.endswith('.egg-info')
2350 is_dist_info = lower.endswith('.dist-info') and os.path.isdir(
2351 os.path.join(path_item, entry)
2352 )
2353 is_meta = is_egg_info or is_dist_info
2354 return (
2355 distributions_from_metadata
2356 if is_meta
2357 else find_distributions
2358 if not only and _is_egg_path(entry)
2359 else resolve_egg_link
2360 if not only and lower.endswith('.egg-link')
2361 else NoDists()
2362 )
2363
2364
2365 class NoDists:
2366 """
2367 >>> bool(NoDists())
2368 False
2369
2370 >>> list(NoDists()('anything'))
2371 []
2372 """
2373
2374 def __bool__(self) -> Literal[False]:
2375 return False
2376
2377 def __call__(self, fullpath: object):
2378 return iter(())
2379
2380
2381 def safe_listdir(path: StrOrBytesPath):
2382 """
2383 Attempt to list contents of path, but suppress some exceptions.
2384 """
2385 try:
2386 return os.listdir(path)
2387 except (PermissionError, NotADirectoryError):
2388 pass
2389 except OSError as e:
2390 # Ignore the directory if does not exist, not a directory or
2391 # permission denied
2392 if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT):
2393 raise
2394 return ()
2395
2396
2397 def distributions_from_metadata(path: str):
2398 root = os.path.dirname(path)
2399 if os.path.isdir(path):
2400 if len(os.listdir(path)) == 0:
2401 # empty metadata dir; skip
2402 return
2403 metadata: _MetadataType = PathMetadata(root, path)
2404 else:
2405 metadata = FileMetadata(path)
2406 entry = os.path.basename(path)
2407 yield Distribution.from_location(
2408 root,
2409 entry,
2410 metadata,
2411 precedence=DEVELOP_DIST,
2412 )
2413
2414
2415 def non_empty_lines(path):
2416 """
2417 Yield non-empty lines from file at path
2418 """
2419 for line in _read_utf8_with_fallback(path).splitlines():
2420 line = line.strip()
2421 if line:
2422 yield line
2423
2424
2425 def resolve_egg_link(path):
2426 """
2427 Given a path to an .egg-link, resolve distributions
2428 present in the referenced path.
2429 """
2430 referenced_paths = non_empty_lines(path)
2431 resolved_paths = (
2432 os.path.join(os.path.dirname(path), ref) for ref in referenced_paths
2433 )
2434 dist_groups = map(find_distributions, resolved_paths)
2435 return next(dist_groups, ())
2436
2437
2438 if hasattr(pkgutil, 'ImpImporter'):
2439 register_finder(pkgutil.ImpImporter, find_on_path)
2440
2441 register_finder(importlib.machinery.FileFinder, find_on_path)
2442
2443 _namespace_handlers: dict[type, _NSHandlerType[Any]] = _declare_state(
2444 'dict', '_namespace_handlers', {}
2445 )
2446 _namespace_packages: dict[str | None, list[str]] = _declare_state(
2447 'dict', '_namespace_packages', {}
2448 )
2449
2450
2451 def register_namespace_handler(
2452 importer_type: type[_T], namespace_handler: _NSHandlerType[_T]
2453 ) -> None:
2454 """Register `namespace_handler` to declare namespace packages
2455
2456 `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
2457 handler), and `namespace_handler` is a callable like this::
2458
2459 def namespace_handler(importer, path_entry, moduleName, module):
2460 # return a path_entry to use for child packages
2461
2462 Namespace handlers are only called if the importer object has already
2463 agreed that it can handle the relevant path item, and they should only
2464 return a subpath if the module __path__ does not already contain an
2465 equivalent subpath. For an example namespace handler, see
2466 ``pkg_resources.file_ns_handler``.
2467 """
2468 _namespace_handlers[importer_type] = namespace_handler
2469
2470
2471 def _handle_ns(packageName, path_item):
2472 """Ensure that named package includes a subpath of path_item (if needed)"""
2473
2474 importer = get_importer(path_item)
2475 if importer is None:
2476 return None
2477
2478 # use find_spec (PEP 451) and fall-back to find_module (PEP 302)
2479 try:
2480 spec = importer.find_spec(packageName)
2481 except AttributeError:
2482 # capture warnings due to #1111
2483 with warnings.catch_warnings():
2484 warnings.simplefilter("ignore")
2485 loader = importer.find_module(packageName)
2486 else:
2487 loader = spec.loader if spec else None
2488
2489 if loader is None:
2490 return None
2491 module = sys.modules.get(packageName)
2492 if module is None:
2493 module = sys.modules[packageName] = types.ModuleType(packageName)
2494 module.__path__ = []
2495 _set_parent_ns(packageName)
2496 elif not hasattr(module, '__path__'):
2497 raise TypeError("Not a package:", packageName)
2498 handler = _find_adapter(_namespace_handlers, importer)
2499 subpath = handler(importer, path_item, packageName, module)
2500 if subpath is not None:
2501 path = module.__path__
2502 path.append(subpath)
2503 importlib.import_module(packageName)
2504 _rebuild_mod_path(path, packageName, module)
2505 return subpath
2506
2507
2508 def _rebuild_mod_path(orig_path, package_name, module: types.ModuleType):
2509 """
2510 Rebuild module.__path__ ensuring that all entries are ordered
2511 corresponding to their sys.path order
2512 """
2513 sys_path = [_normalize_cached(p) for p in sys.path]
2514
2515 def safe_sys_path_index(entry):
2516 """
2517 Workaround for #520 and #513.
2518 """
2519 try:
2520 return sys_path.index(entry)
2521 except ValueError:
2522 return float('inf')
2523
2524 def position_in_sys_path(path):
2525 """
2526 Return the ordinal of the path based on its position in sys.path
2527 """
2528 path_parts = path.split(os.sep)
2529 module_parts = package_name.count('.') + 1
2530 parts = path_parts[:-module_parts]
2531 return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
2532
2533 new_path = sorted(orig_path, key=position_in_sys_path)
2534 new_path = [_normalize_cached(p) for p in new_path]
2535
2536 if isinstance(module.__path__, list):
2537 module.__path__[:] = new_path
2538 else:
2539 module.__path__ = new_path
2540
2541
2542 def declare_namespace(packageName: str) -> None:
2543 """Declare that package 'packageName' is a namespace package"""
2544
2545 msg = (
2546 f"Deprecated call to `pkg_resources.declare_namespace({packageName!r})`.\n"
2547 "Implementing implicit namespace packages (as specified in PEP 420) "
2548 "is preferred to `pkg_resources.declare_namespace`. "
2549 "See https://setuptools.pypa.io/en/latest/references/"
2550 "keywords.html#keyword-namespace-packages"
2551 )
2552 warnings.warn(msg, DeprecationWarning, stacklevel=2)
2553
2554 _imp.acquire_lock()
2555 try:
2556 if packageName in _namespace_packages:
2557 return
2558
2559 path: MutableSequence[str] = sys.path
2560 parent, _, _ = packageName.rpartition('.')
2561
2562 if parent:
2563 declare_namespace(parent)
2564 if parent not in _namespace_packages:
2565 __import__(parent)
2566 try:
2567 path = sys.modules[parent].__path__
2568 except AttributeError as e:
2569 raise TypeError("Not a package:", parent) from e
2570
2571 # Track what packages are namespaces, so when new path items are added,
2572 # they can be updated
2573 _namespace_packages.setdefault(parent or None, []).append(packageName)
2574 _namespace_packages.setdefault(packageName, [])
2575
2576 for path_item in path:
2577 # Ensure all the parent's path items are reflected in the child,
2578 # if they apply
2579 _handle_ns(packageName, path_item)
2580
2581 finally:
2582 _imp.release_lock()
2583
2584
2585 def fixup_namespace_packages(path_item: str, parent: str | None = None) -> None:
2586 """Ensure that previously-declared namespace packages include path_item"""
2587 _imp.acquire_lock()
2588 try:
2589 for package in _namespace_packages.get(parent, ()):
2590 subpath = _handle_ns(package, path_item)
2591 if subpath:
2592 fixup_namespace_packages(subpath, package)
2593 finally:
2594 _imp.release_lock()
2595
2596
2597 def file_ns_handler(
2598 importer: object,
2599 path_item: StrPath,
2600 packageName: str,
2601 module: types.ModuleType,
2602 ):
2603 """Compute an ns-package subpath for a filesystem or zipfile importer"""
2604
2605 subpath = os.path.join(path_item, packageName.split('.')[-1])
2606 normalized = _normalize_cached(subpath)
2607 for item in module.__path__:
2608 if _normalize_cached(item) == normalized:
2609 break
2610 else:
2611 # Only return the path if it's not already there
2612 return subpath
2613
2614
2615 if hasattr(pkgutil, 'ImpImporter'):
2616 register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
2617
2618 register_namespace_handler(zipimport.zipimporter, file_ns_handler)
2619 register_namespace_handler(importlib.machinery.FileFinder, file_ns_handler)
2620
2621
2622 def null_ns_handler(
2623 importer: object,
2624 path_item: str | None,
2625 packageName: str | None,
2626 module: _ModuleLike | None,
2627 ):
2628 return None
2629
2630
2631 register_namespace_handler(object, null_ns_handler)
2632
2633
2634 @overload
2635 def normalize_path(filename: StrPath) -> str: ...
2636 @overload
2637 def normalize_path(filename: BytesPath) -> bytes: ...
2638 def normalize_path(filename: StrOrBytesPath):
2639 """Normalize a file/dir name for comparison purposes"""
2640 return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
2641
2642
2643 def _cygwin_patch(filename: StrOrBytesPath): # pragma: nocover
2644 """
2645 Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
2646 symlink components. Using
2647 os.path.abspath() works around this limitation. A fix in os.getcwd()
2648 would probably better, in Cygwin even more so, except
2649 that this seems to be by design...
2650 """
2651 return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
2652
2653
2654 if TYPE_CHECKING:
2655 # https://github.com/python/mypy/issues/16261
2656 # https://github.com/python/typeshed/issues/6347
2657 @overload
2658 def _normalize_cached(filename: StrPath) -> str: ...
2659 @overload
2660 def _normalize_cached(filename: BytesPath) -> bytes: ...
2661 def _normalize_cached(filename: StrOrBytesPath) -> str | bytes: ...
2662
2663 else:
2664
2665 @functools.lru_cache(maxsize=None)
2666 def _normalize_cached(filename):
2667 return normalize_path(filename)
2668
2669
2670 def _is_egg_path(path):
2671 """
2672 Determine if given path appears to be an egg.
2673 """
2674 return _is_zip_egg(path) or _is_unpacked_egg(path)
2675
2676
2677 def _is_zip_egg(path):
2678 return (
2679 path.lower().endswith('.egg')
2680 and os.path.isfile(path)
2681 and zipfile.is_zipfile(path)
2682 )
2683
2684
2685 def _is_unpacked_egg(path):
2686 """
2687 Determine if given path appears to be an unpacked egg.
2688 """
2689 return path.lower().endswith('.egg') and os.path.isfile(
2690 os.path.join(path, 'EGG-INFO', 'PKG-INFO')
2691 )
2692
2693
2694 def _set_parent_ns(packageName):
2695 parts = packageName.split('.')
2696 name = parts.pop()
2697 if parts:
2698 parent = '.'.join(parts)
2699 setattr(sys.modules[parent], name, sys.modules[packageName])
2700
2701
2702 MODULE = re.compile(r"\w+(\.\w+)*$").match
2703 EGG_NAME = re.compile(
2704 r"""
2705 (?P<name>[^-]+) (
2706 -(?P<ver>[^-]+) (
2707 -py(?P<pyver>[^-]+) (
2708 -(?P<plat>.+)
2709 )?
2710 )?
2711 )?
2712 """,
2713 re.VERBOSE | re.IGNORECASE,
2714 ).match
2715
2716
2717 class EntryPoint:
2718 """Object representing an advertised importable object"""
2719
2720 def __init__(
2721 self,
2722 name: str,
2723 module_name: str,
2724 attrs: Iterable[str] = (),
2725 extras: Iterable[str] = (),
2726 dist: Distribution | None = None,
2727 ) -> None:
2728 if not MODULE(module_name):
2729 raise ValueError("Invalid module name", module_name)
2730 self.name = name
2731 self.module_name = module_name
2732 self.attrs = tuple(attrs)
2733 self.extras = tuple(extras)
2734 self.dist = dist
2735
2736 def __str__(self) -> str:
2737 s = "%s = %s" % (self.name, self.module_name)
2738 if self.attrs:
2739 s += ':' + '.'.join(self.attrs)
2740 if self.extras:
2741 s += ' [%s]' % ','.join(self.extras)
2742 return s
2743
2744 def __repr__(self) -> str:
2745 return "EntryPoint.parse(%r)" % str(self)
2746
2747 @overload
2748 def load(
2749 self,
2750 require: Literal[True] = True,
2751 env: Environment | None = None,
2752 installer: _InstallerType | None = None,
2753 ) -> _ResolvedEntryPoint: ...
2754 @overload
2755 def load(
2756 self,
2757 require: Literal[False],
2758 *args: Any,
2759 **kwargs: Any,
2760 ) -> _ResolvedEntryPoint: ...
2761 def load(
2762 self,
2763 require: bool = True,
2764 *args: Environment | _InstallerType | None,
2765 **kwargs: Environment | _InstallerType | None,
2766 ) -> _ResolvedEntryPoint:
2767 """
2768 Require packages for this EntryPoint, then resolve it.
2769 """
2770 if not require or args or kwargs:
2771 warnings.warn(
2772 "Parameters to load are deprecated. Call .resolve and "
2773 ".require separately.",
2774 PkgResourcesDeprecationWarning,
2775 stacklevel=2,
2776 )
2777 if require:
2778 # We could pass `env` and `installer` directly,
2779 # but keeping `*args` and `**kwargs` for backwards compatibility
2780 self.require(*args, **kwargs) # type: ignore
2781 return self.resolve()
2782
2783 def resolve(self) -> _ResolvedEntryPoint:
2784 """
2785 Resolve the entry point from its module and attrs.
2786 """
2787 module = __import__(self.module_name, fromlist=['__name__'], level=0)
2788 try:
2789 return functools.reduce(getattr, self.attrs, module)
2790 except AttributeError as exc:
2791 raise ImportError(str(exc)) from exc
2792
2793 def require(
2794 self,
2795 env: Environment | None = None,
2796 installer: _InstallerType | None = None,
2797 ) -> None:
2798 if not self.dist:
2799 error_cls = UnknownExtra if self.extras else AttributeError
2800 raise error_cls("Can't require() without a distribution", self)
2801
2802 # Get the requirements for this entry point with all its extras and
2803 # then resolve them. We have to pass `extras` along when resolving so
2804 # that the working set knows what extras we want. Otherwise, for
2805 # dist-info distributions, the working set will assume that the
2806 # requirements for that extra are purely optional and skip over them.
2807 reqs = self.dist.requires(self.extras)
2808 items = working_set.resolve(reqs, env, installer, extras=self.extras)
2809 list(map(working_set.add, items))
2810
2811 pattern = re.compile(
2812 r'\s*'
2813 r'(?P<name>.+?)\s*'
2814 r'=\s*'
2815 r'(?P<module>[\w.]+)\s*'
2816 r'(:\s*(?P<attr>[\w.]+))?\s*'
2817 r'(?P<extras>\[.*\])?\s*$'
2818 )
2819
2820 @classmethod
2821 def parse(cls, src: str, dist: Distribution | None = None) -> Self:
2822 """Parse a single entry point from string `src`
2823
2824 Entry point syntax follows the form::
2825
2826 name = some.module:some.attr [extra1, extra2]
2827
2828 The entry name and module name are required, but the ``:attrs`` and
2829 ``[extras]`` parts are optional
2830 """
2831 m = cls.pattern.match(src)
2832 if not m:
2833 msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
2834 raise ValueError(msg, src)
2835 res = m.groupdict()
2836 extras = cls._parse_extras(res['extras'])
2837 attrs = res['attr'].split('.') if res['attr'] else ()
2838 return cls(res['name'], res['module'], attrs, extras, dist)
2839
2840 @classmethod
2841 def _parse_extras(cls, extras_spec):
2842 if not extras_spec:
2843 return ()
2844 req = Requirement.parse('x' + extras_spec)
2845 if req.specs:
2846 raise ValueError
2847 return req.extras
2848
2849 @classmethod
2850 def parse_group(
2851 cls,
2852 group: str,
2853 lines: _NestedStr,
2854 dist: Distribution | None = None,
2855 ) -> dict[str, Self]:
2856 """Parse an entry point group"""
2857 if not MODULE(group):
2858 raise ValueError("Invalid group name", group)
2859 this: dict[str, Self] = {}
2860 for line in yield_lines(lines):
2861 ep = cls.parse(line, dist)
2862 if ep.name in this:
2863 raise ValueError("Duplicate entry point", group, ep.name)
2864 this[ep.name] = ep
2865 return this
2866
2867 @classmethod
2868 def parse_map(
2869 cls,
2870 data: str | Iterable[str] | dict[str, str | Iterable[str]],
2871 dist: Distribution | None = None,
2872 ) -> dict[str, dict[str, Self]]:
2873 """Parse a map of entry point groups"""
2874 _data: Iterable[tuple[str | None, str | Iterable[str]]]
2875 if isinstance(data, dict):
2876 _data = data.items()
2877 else:
2878 _data = split_sections(data)
2879 maps: dict[str, dict[str, Self]] = {}
2880 for group, lines in _data:
2881 if group is None:
2882 if not lines:
2883 continue
2884 raise ValueError("Entry points must be listed in groups")
2885 group = group.strip()
2886 if group in maps:
2887 raise ValueError("Duplicate group name", group)
2888 maps[group] = cls.parse_group(group, lines, dist)
2889 return maps
2890
2891
2892 def _version_from_file(lines):
2893 """
2894 Given an iterable of lines from a Metadata file, return
2895 the value of the Version field, if present, or None otherwise.
2896 """
2897
2898 def is_version_line(line):
2899 return line.lower().startswith('version:')
2900
2901 version_lines = filter(is_version_line, lines)
2902 line = next(iter(version_lines), '')
2903 _, _, value = line.partition(':')
2904 return safe_version(value.strip()) or None
2905
2906
2907 class Distribution:
2908 """Wrap an actual or potential sys.path entry w/metadata"""
2909
2910 PKG_INFO = 'PKG-INFO'
2911
2912 def __init__(
2913 self,
2914 location: str | None = None,
2915 metadata: _MetadataType = None,
2916 project_name: str | None = None,
2917 version: str | None = None,
2918 py_version: str | None = PY_MAJOR,
2919 platform: str | None = None,
2920 precedence: int = EGG_DIST,
2921 ) -> None:
2922 self.project_name = safe_name(project_name or 'Unknown')
2923 if version is not None:
2924 self._version = safe_version(version)
2925 self.py_version = py_version
2926 self.platform = platform
2927 self.location = location
2928 self.precedence = precedence
2929 self._provider = metadata or empty_provider
2930
2931 @classmethod
2932 def from_location(
2933 cls,
2934 location: str,
2935 basename: StrPath,
2936 metadata: _MetadataType = None,
2937 **kw: int, # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
2938 ) -> Distribution:
2939 project_name, version, py_version, platform = [None] * 4
2940 basename, ext = os.path.splitext(basename)
2941 if ext.lower() in _distributionImpl:
2942 cls = _distributionImpl[ext.lower()]
2943
2944 match = EGG_NAME(basename)
2945 if match:
2946 project_name, version, py_version, platform = match.group(
2947 'name', 'ver', 'pyver', 'plat'
2948 )
2949 return cls(
2950 location,
2951 metadata,
2952 project_name=project_name,
2953 version=version,
2954 py_version=py_version,
2955 platform=platform,
2956 **kw,
2957 )._reload_version()
2958
2959 def _reload_version(self):
2960 return self
2961
2962 @property
2963 def hashcmp(self):
2964 return (
2965 self._forgiving_parsed_version,
2966 self.precedence,
2967 self.key,
2968 self.location,
2969 self.py_version or '',
2970 self.platform or '',
2971 )
2972
2973 def __hash__(self) -> int:
2974 return hash(self.hashcmp)
2975
2976 def __lt__(self, other: Distribution) -> bool:
2977 return self.hashcmp < other.hashcmp
2978
2979 def __le__(self, other: Distribution) -> bool:
2980 return self.hashcmp <= other.hashcmp
2981
2982 def __gt__(self, other: Distribution) -> bool:
2983 return self.hashcmp > other.hashcmp
2984
2985 def __ge__(self, other: Distribution) -> bool:
2986 return self.hashcmp >= other.hashcmp
2987
2988 def __eq__(self, other: object) -> bool:
2989 if not isinstance(other, self.__class__):
2990 # It's not a Distribution, so they are not equal
2991 return False
2992 return self.hashcmp == other.hashcmp
2993
2994 def __ne__(self, other: object) -> bool:
2995 return not self == other
2996
2997 # These properties have to be lazy so that we don't have to load any
2998 # metadata until/unless it's actually needed. (i.e., some distributions
2999 # may not know their name or version without loading PKG-INFO)
3000
3001 @property
3002 def key(self):
3003 try:
3004 return self._key
3005 except AttributeError:
3006 self._key = key = self.project_name.lower()
3007 return key
3008
3009 @property
3010 def parsed_version(self):
3011 if not hasattr(self, "_parsed_version"):
3012 try:
3013 self._parsed_version = parse_version(self.version)
3014 except packaging.version.InvalidVersion as ex:
3015 info = f"(package: {self.project_name})"
3016 if hasattr(ex, "add_note"):
3017 ex.add_note(info) # PEP 678
3018 raise
3019 raise packaging.version.InvalidVersion(f"{str(ex)} {info}") from None
3020
3021 return self._parsed_version
3022
3023 @property
3024 def _forgiving_parsed_version(self):
3025 try:
3026 return self.parsed_version
3027 except packaging.version.InvalidVersion as ex:
3028 self._parsed_version = parse_version(_forgiving_version(self.version))
3029
3030 notes = "\n".join(getattr(ex, "__notes__", [])) # PEP 678
3031 msg = f"""!!\n\n
3032 *************************************************************************
3033 {str(ex)}\n{notes}
3034
3035 This is a long overdue deprecation.
3036 For the time being, `pkg_resources` will use `{self._parsed_version}`
3037 as a replacement to avoid breaking existing environments,
3038 but no future compatibility is guaranteed.
3039
3040 If you maintain package {self.project_name} you should implement
3041 the relevant changes to adequate the project to PEP 440 immediately.
3042 *************************************************************************
3043 \n\n!!
3044 """
3045 warnings.warn(msg, DeprecationWarning)
3046
3047 return self._parsed_version
3048
3049 @property
3050 def version(self):
3051 try:
3052 return self._version
3053 except AttributeError as e:
3054 version = self._get_version()
3055 if version is None:
3056 path = self._get_metadata_path_for_display(self.PKG_INFO)
3057 msg = ("Missing 'Version:' header and/or {} file at path: {}").format(
3058 self.PKG_INFO, path
3059 )
3060 raise ValueError(msg, self) from e
3061
3062 return version
3063
3064 @property
3065 def _dep_map(self):
3066 """
3067 A map of extra to its list of (direct) requirements
3068 for this distribution, including the null extra.
3069 """
3070 try:
3071 return self.__dep_map
3072 except AttributeError:
3073 self.__dep_map = self._filter_extras(self._build_dep_map())
3074 return self.__dep_map
3075
3076 @staticmethod
3077 def _filter_extras(
3078 dm: dict[str | None, list[Requirement]],
3079 ) -> dict[str | None, list[Requirement]]:
3080 """
3081 Given a mapping of extras to dependencies, strip off
3082 environment markers and filter out any dependencies
3083 not matching the markers.
3084 """
3085 for extra in list(filter(None, dm)):
3086 new_extra: str | None = extra
3087 reqs = dm.pop(extra)
3088 new_extra, _, marker = extra.partition(':')
3089 fails_marker = marker and (
3090 invalid_marker(marker) or not evaluate_marker(marker)
3091 )
3092 if fails_marker:
3093 reqs = []
3094 new_extra = safe_extra(new_extra) or None
3095
3096 dm.setdefault(new_extra, []).extend(reqs)
3097 return dm
3098
3099 def _build_dep_map(self):
3100 dm = {}
3101 for name in 'requires.txt', 'depends.txt':
3102 for extra, reqs in split_sections(self._get_metadata(name)):
3103 dm.setdefault(extra, []).extend(parse_requirements(reqs))
3104 return dm
3105
3106 def requires(self, extras: Iterable[str] = ()) -> list[Requirement]:
3107 """List of Requirements needed for this distro if `extras` are used"""
3108 dm = self._dep_map
3109 deps: list[Requirement] = []
3110 deps.extend(dm.get(None, ()))
3111 for ext in extras:
3112 try:
3113 deps.extend(dm[safe_extra(ext)])
3114 except KeyError as e:
3115 raise UnknownExtra(
3116 "%s has no such extra feature %r" % (self, ext)
3117 ) from e
3118 return deps
3119
3120 def _get_metadata_path_for_display(self, name):
3121 """
3122 Return the path to the given metadata file, if available.
3123 """
3124 try:
3125 # We need to access _get_metadata_path() on the provider object
3126 # directly rather than through this class's __getattr__()
3127 # since _get_metadata_path() is marked private.
3128 path = self._provider._get_metadata_path(name)
3129
3130 # Handle exceptions e.g. in case the distribution's metadata
3131 # provider doesn't support _get_metadata_path().
3132 except Exception:
3133 return '[could not detect]'
3134
3135 return path
3136
3137 def _get_metadata(self, name):
3138 if self.has_metadata(name):
3139 yield from self.get_metadata_lines(name)
3140
3141 def _get_version(self):
3142 lines = self._get_metadata(self.PKG_INFO)
3143 return _version_from_file(lines)
3144
3145 def activate(self, path: list[str] | None = None, replace: bool = False) -> None:
3146 """Ensure distribution is importable on `path` (default=sys.path)"""
3147 if path is None:
3148 path = sys.path
3149 self.insert_on(path, replace=replace)
3150 if path is sys.path and self.location is not None:
3151 fixup_namespace_packages(self.location)
3152 for pkg in self._get_metadata('namespace_packages.txt'):
3153 if pkg in sys.modules:
3154 declare_namespace(pkg)
3155
3156 def egg_name(self):
3157 """Return what this distribution's standard .egg filename should be"""
3158 filename = "%s-%s-py%s" % (
3159 to_filename(self.project_name),
3160 to_filename(self.version),
3161 self.py_version or PY_MAJOR,
3162 )
3163
3164 if self.platform:
3165 filename += '-' + self.platform
3166 return filename
3167
3168 def __repr__(self) -> str:
3169 if self.location:
3170 return "%s (%s)" % (self, self.location)
3171 else:
3172 return str(self)
3173
3174 def __str__(self) -> str:
3175 try:
3176 version = getattr(self, 'version', None)
3177 except ValueError:
3178 version = None
3179 version = version or "[unknown version]"
3180 return "%s %s" % (self.project_name, version)
3181
3182 def __getattr__(self, attr: str):
3183 """Delegate all unrecognized public attributes to .metadata provider"""
3184 if attr.startswith('_'):
3185 raise AttributeError(attr)
3186 return getattr(self._provider, attr)
3187
3188 def __dir__(self):
3189 return list(
3190 set(super().__dir__())
3191 | set(attr for attr in self._provider.__dir__() if not attr.startswith('_'))
3192 )
3193
3194 @classmethod
3195 def from_filename(
3196 cls,
3197 filename: StrPath,
3198 metadata: _MetadataType = None,
3199 **kw: int, # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
3200 ) -> Distribution:
3201 return cls.from_location(
3202 _normalize_cached(filename), os.path.basename(filename), metadata, **kw
3203 )
3204
3205 def as_requirement(self):
3206 """Return a ``Requirement`` that matches this distribution exactly"""
3207 if isinstance(self.parsed_version, packaging.version.Version):
3208 spec = "%s==%s" % (self.project_name, self.parsed_version)
3209 else:
3210 spec = "%s===%s" % (self.project_name, self.parsed_version)
3211
3212 return Requirement.parse(spec)
3213
3214 def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint:
3215 """Return the `name` entry point of `group` or raise ImportError"""
3216 ep = self.get_entry_info(group, name)
3217 if ep is None:
3218 raise ImportError("Entry point %r not found" % ((group, name),))
3219 return ep.load()
3220
3221 @overload
3222 def get_entry_map(self, group: None = None) -> dict[str, dict[str, EntryPoint]]: ...
3223 @overload
3224 def get_entry_map(self, group: str) -> dict[str, EntryPoint]: ...
3225 def get_entry_map(self, group: str | None = None):
3226 """Return the entry point map for `group`, or the full entry map"""
3227 if not hasattr(self, "_ep_map"):
3228 self._ep_map = EntryPoint.parse_map(
3229 self._get_metadata('entry_points.txt'), self
3230 )
3231 if group is not None:
3232 return self._ep_map.get(group, {})
3233 return self._ep_map
3234
3235 def get_entry_info(self, group: str, name: str) -> EntryPoint | None:
3236 """Return the EntryPoint object for `group`+`name`, or ``None``"""
3237 return self.get_entry_map(group).get(name)
3238
3239 # FIXME: 'Distribution.insert_on' is too complex (13)
3240 def insert_on( # noqa: C901
3241 self,
3242 path: list[str],
3243 loc=None,
3244 replace: bool = False,
3245 ) -> None:
3246 """Ensure self.location is on path
3247
3248 If replace=False (default):
3249 - If location is already in path anywhere, do nothing.
3250 - Else:
3251 - If it's an egg and its parent directory is on path,
3252 insert just ahead of the parent.
3253 - Else: add to the end of path.
3254 If replace=True:
3255 - If location is already on path anywhere (not eggs)
3256 or higher priority than its parent (eggs)
3257 do nothing.
3258 - Else:
3259 - If it's an egg and its parent directory is on path,
3260 insert just ahead of the parent,
3261 removing any lower-priority entries.
3262 - Else: add it to the front of path.
3263 """
3264
3265 loc = loc or self.location
3266 if not loc:
3267 return
3268
3269 nloc = _normalize_cached(loc)
3270 bdir = os.path.dirname(nloc)
3271 npath = [(p and _normalize_cached(p) or p) for p in path]
3272
3273 for p, item in enumerate(npath):
3274 if item == nloc:
3275 if replace:
3276 break
3277 else:
3278 # don't modify path (even removing duplicates) if
3279 # found and not replace
3280 return
3281 elif item == bdir and self.precedence == EGG_DIST:
3282 # if it's an .egg, give it precedence over its directory
3283 # UNLESS it's already been added to sys.path and replace=False
3284 if (not replace) and nloc in npath[p:]:
3285 return
3286 if path is sys.path:
3287 self.check_version_conflict()
3288 path.insert(p, loc)
3289 npath.insert(p, nloc)
3290 break
3291 else:
3292 if path is sys.path:
3293 self.check_version_conflict()
3294 if replace:
3295 path.insert(0, loc)
3296 else:
3297 path.append(loc)
3298 return
3299
3300 # p is the spot where we found or inserted loc; now remove duplicates
3301 while True:
3302 try:
3303 np = npath.index(nloc, p + 1)
3304 except ValueError:
3305 break
3306 else:
3307 del npath[np], path[np]
3308 # ha!
3309 p = np
3310
3311 return
3312
3313 def check_version_conflict(self):
3314 if self.key == 'setuptools':
3315 # ignore the inevitable setuptools self-conflicts :(
3316 return
3317
3318 nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
3319 loc = normalize_path(self.location)
3320 for modname in self._get_metadata('top_level.txt'):
3321 if (
3322 modname not in sys.modules
3323 or modname in nsp
3324 or modname in _namespace_packages
3325 ):
3326 continue
3327 if modname in ('pkg_resources', 'setuptools', 'site'):
3328 continue
3329 fn = getattr(sys.modules[modname], '__file__', None)
3330 if fn and (
3331 normalize_path(fn).startswith(loc) or fn.startswith(self.location)
3332 ):
3333 continue
3334 issue_warning(
3335 "Module %s was already imported from %s, but %s is being added"
3336 " to sys.path" % (modname, fn, self.location),
3337 )
3338
3339 def has_version(self):
3340 try:
3341 self.version
3342 except ValueError:
3343 issue_warning("Unbuilt egg for " + repr(self))
3344 return False
3345 except SystemError:
3346 # TODO: remove this except clause when python/cpython#103632 is fixed.
3347 return False
3348 return True
3349
3350 def clone(self, **kw: str | int | IResourceProvider | None) -> Self:
3351 """Copy this distribution, substituting in any changed keyword args"""
3352 names = 'project_name version py_version platform location precedence'
3353 for attr in names.split():
3354 kw.setdefault(attr, getattr(self, attr, None))
3355 kw.setdefault('metadata', self._provider)
3356 # Unsafely unpacking. But keeping **kw for backwards and subclassing compatibility
3357 return self.__class__(**kw) # type:ignore[arg-type]
3358
3359 @property
3360 def extras(self):
3361 return [dep for dep in self._dep_map if dep]
3362
3363
3364 class EggInfoDistribution(Distribution):
3365 def _reload_version(self):
3366 """
3367 Packages installed by distutils (e.g. numpy or scipy),
3368 which uses an old safe_version, and so
3369 their version numbers can get mangled when
3370 converted to filenames (e.g., 1.11.0.dev0+2329eae to
3371 1.11.0.dev0_2329eae). These distributions will not be
3372 parsed properly
3373 downstream by Distribution and safe_version, so
3374 take an extra step and try to get the version number from
3375 the metadata file itself instead of the filename.
3376 """
3377 md_version = self._get_version()
3378 if md_version:
3379 self._version = md_version
3380 return self
3381
3382
3383 class DistInfoDistribution(Distribution):
3384 """
3385 Wrap an actual or potential sys.path entry
3386 w/metadata, .dist-info style.
3387 """
3388
3389 PKG_INFO = 'METADATA'
3390 EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
3391
3392 @property
3393 def _parsed_pkg_info(self):
3394 """Parse and cache metadata"""
3395 try:
3396 return self._pkg_info
3397 except AttributeError:
3398 metadata = self.get_metadata(self.PKG_INFO)
3399 self._pkg_info = email.parser.Parser().parsestr(metadata)
3400 return self._pkg_info
3401
3402 @property
3403 def _dep_map(self):
3404 try:
3405 return self.__dep_map
3406 except AttributeError:
3407 self.__dep_map = self._compute_dependencies()
3408 return self.__dep_map
3409
3410 def _compute_dependencies(self) -> dict[str | None, list[Requirement]]:
3411 """Recompute this distribution's dependencies."""
3412 self.__dep_map: dict[str | None, list[Requirement]] = {None: []}
3413
3414 reqs: list[Requirement] = []
3415 # Including any condition expressions
3416 for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
3417 reqs.extend(parse_requirements(req))
3418
3419 def reqs_for_extra(extra):
3420 for req in reqs:
3421 if not req.marker or req.marker.evaluate({'extra': extra}):
3422 yield req
3423
3424 common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None)))
3425 self.__dep_map[None].extend(common)
3426
3427 for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
3428 s_extra = safe_extra(extra.strip())
3429 self.__dep_map[s_extra] = [
3430 r for r in reqs_for_extra(extra) if r not in common
3431 ]
3432
3433 return self.__dep_map
3434
3435
3436 _distributionImpl = {
3437 '.egg': Distribution,
3438 '.egg-info': EggInfoDistribution,
3439 '.dist-info': DistInfoDistribution,
3440 }
3441
3442
3443 def issue_warning(*args, **kw):
3444 level = 1
3445 g = globals()
3446 try:
3447 # find the first stack frame that is *not* code in
3448 # the pkg_resources module, to use for the warning
3449 while sys._getframe(level).f_globals is g:
3450 level += 1
3451 except ValueError:
3452 pass
3453 warnings.warn(stacklevel=level + 1, *args, **kw)
3454
3455
3456 def parse_requirements(strs: _NestedStr) -> map[Requirement]:
3457 """
3458 Yield ``Requirement`` objects for each specification in `strs`.
3459
3460 `strs` must be a string, or a (possibly-nested) iterable thereof.
3461 """
3462 return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs))))
3463
3464
3465 class RequirementParseError(packaging.requirements.InvalidRequirement):
3466 "Compatibility wrapper for InvalidRequirement"
3467
3468
3469 class Requirement(packaging.requirements.Requirement):
3470 # prefer variable length tuple to set (as found in
3471 # packaging.requirements.Requirement)
3472 extras: tuple[str, ...] # type: ignore[assignment]
3473
3474 def __init__(self, requirement_string: str) -> None:
3475 """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
3476 super().__init__(requirement_string)
3477 self.unsafe_name = self.name
3478 project_name = safe_name(self.name)
3479 self.project_name, self.key = project_name, project_name.lower()
3480 self.specs = [(spec.operator, spec.version) for spec in self.specifier]
3481 self.extras = tuple(map(safe_extra, self.extras))
3482 self.hashCmp = (
3483 self.key,
3484 self.url,
3485 self.specifier,
3486 frozenset(self.extras),
3487 str(self.marker) if self.marker else None,
3488 )
3489 self.__hash = hash(self.hashCmp)
3490
3491 def __eq__(self, other: object) -> bool:
3492 return isinstance(other, Requirement) and self.hashCmp == other.hashCmp
3493
3494 def __ne__(self, other: object) -> bool:
3495 return not self == other
3496
3497 def __contains__(
3498 self, item: Distribution | packaging.specifiers.UnparsedVersion
3499 ) -> bool:
3500 if isinstance(item, Distribution):
3501 if item.key != self.key:
3502 return False
3503
3504 version = item.version
3505 else:
3506 version = item
3507
3508 # Allow prereleases always in order to match the previous behavior of
3509 # this method. In the future this should be smarter and follow PEP 440
3510 # more accurately.
3511 return self.specifier.contains(
3512 version,
3513 prereleases=True,
3514 )
3515
3516 def __hash__(self) -> int:
3517 return self.__hash
3518
3519 def __repr__(self) -> str:
3520 return "Requirement.parse(%r)" % str(self)
3521
3522 @staticmethod
3523 def parse(s: str | Iterable[str]) -> Requirement:
3524 (req,) = parse_requirements(s)
3525 return req
3526
3527
3528 def _always_object(classes):
3529 """
3530 Ensure object appears in the mro even
3531 for old-style classes.
3532 """
3533 if object not in classes:
3534 return classes + (object,)
3535 return classes
3536
3537
3538 def _find_adapter(registry: Mapping[type, _AdapterT], ob: object) -> _AdapterT:
3539 """Return an adapter factory for `ob` from `registry`"""
3540 types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
3541 for t in types:
3542 if t in registry:
3543 return registry[t]
3544 # _find_adapter would previously return None, and immediately be called.
3545 # So we're raising a TypeError to keep backward compatibility if anyone depended on that behaviour.
3546 raise TypeError(f"Could not find adapter for {registry} and {ob}")
3547
3548
3549 def ensure_directory(path: StrOrBytesPath) -> None:
3550 """Ensure that the parent directory of `path` exists"""
3551 dirname = os.path.dirname(path)
3552 os.makedirs(dirname, exist_ok=True)
3553
3554
3555 def _bypass_ensure_directory(path):
3556 """Sandbox-bypassing version of ensure_directory()"""
3557 if not WRITE_SUPPORT:
3558 raise OSError('"os.mkdir" not supported on this platform.')
3559 dirname, filename = split(path)
3560 if dirname and filename and not isdir(dirname):
3561 _bypass_ensure_directory(dirname)
3562 try:
3563 mkdir(dirname, 0o755)
3564 except FileExistsError:
3565 pass
3566
3567
3568 def split_sections(s: _NestedStr) -> Iterator[tuple[str | None, list[str]]]:
3569 """Split a string or iterable thereof into (section, content) pairs
3570
3571 Each ``section`` is a stripped version of the section header ("[section]")
3572 and each ``content`` is a list of stripped lines excluding blank lines and
3573 comment-only lines. If there are any such lines before the first section
3574 header, they're returned in a first ``section`` of ``None``.
3575 """
3576 section = None
3577 content: list[str] = []
3578 for line in yield_lines(s):
3579 if line.startswith("["):
3580 if line.endswith("]"):
3581 if section or content:
3582 yield section, content
3583 section = line[1:-1].strip()
3584 content = []
3585 else:
3586 raise ValueError("Invalid section heading", line)
3587 else:
3588 content.append(line)
3589
3590 # wrap up last segment
3591 yield section, content
3592
3593
3594 def _mkstemp(*args, **kw):
3595 old_open = os.open
3596 try:
3597 # temporarily bypass sandboxing
3598 os.open = os_open
3599 return tempfile.mkstemp(*args, **kw)
3600 finally:
3601 # and then put it back
3602 os.open = old_open
3603
3604
3605 # Silence the PEP440Warning by default, so that end users don't get hit by it
3606 # randomly just because they use pkg_resources. We want to append the rule
3607 # because we want earlier uses of filterwarnings to take precedence over this
3608 # one.
3609 warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
3610
3611
3612 class PkgResourcesDeprecationWarning(Warning):
3613 """
3614 Base class for warning about deprecations in ``pkg_resources``
3615
3616 This class is not derived from ``DeprecationWarning``, and as such is
3617 visible by default.
3618 """
3619
3620
3621 # Ported from ``setuptools`` to avoid introducing an import inter-dependency:
3622 _LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
3623
3624
3625 # This must go before calls to `_call_aside`. See https://github.com/pypa/setuptools/pull/4422
3626 def _read_utf8_with_fallback(file: str, fallback_encoding=_LOCALE_ENCODING) -> str:
3627 """See setuptools.unicode_utils._read_utf8_with_fallback"""
3628 try:
3629 with open(file, "r", encoding="utf-8") as f:
3630 return f.read()
3631 except UnicodeDecodeError: # pragma: no cover
3632 msg = f"""\
3633 ********************************************************************************
3634 `encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`.
3635
3636 This fallback behaviour is considered **deprecated** and future versions of
3637 `setuptools/pkg_resources` may not implement it.
3638
3639 Please encode {file!r} with "utf-8" to ensure future builds will succeed.
3640
3641 If this file was produced by `setuptools` itself, cleaning up the cached files
3642 and re-building/re-installing the package with a newer version of `setuptools`
3643 (e.g. by updating `build-system.requires` in its `pyproject.toml`)
3644 might solve the problem.
3645 ********************************************************************************
3646 """
3647 # TODO: Add a deadline?
3648 # See comment in setuptools.unicode_utils._Utf8EncodingNeeded
3649 warnings.warn(msg, PkgResourcesDeprecationWarning, stacklevel=2)
3650 with open(file, "r", encoding=fallback_encoding) as f:
3651 return f.read()
3652
3653
3654 # from jaraco.functools 1.3
3655 def _call_aside(f, *args, **kwargs):
3656 f(*args, **kwargs)
3657 return f
3658
3659
3660 @_call_aside
3661 def _initialize(g=globals()):
3662 "Set up global resource manager (deliberately not state-saved)"
3663 manager = ResourceManager()
3664 g['_manager'] = manager
3665 g.update(
3666 (name, getattr(manager, name))
3667 for name in dir(manager)
3668 if not name.startswith('_')
3669 )
3670
3671
3672 @_call_aside
3673 def _initialize_master_working_set():
3674 """
3675 Prepare the master working set and make the ``require()``
3676 API available.
3677
3678 This function has explicit effects on the global state
3679 of pkg_resources. It is intended to be invoked once at
3680 the initialization of this module.
3681
3682 Invocation by other packages is unsupported and done
3683 at their own risk.
3684 """
3685 working_set = _declare_state('object', 'working_set', WorkingSet._build_master())
3686
3687 require = working_set.require
3688 iter_entry_points = working_set.iter_entry_points
3689 add_activation_listener = working_set.subscribe
3690 run_script = working_set.run_script
3691 # backward compatibility
3692 run_main = run_script
3693 # Activate all distributions already on sys.path with replace=False and
3694 # ensure that all distributions added to the working set in the future
3695 # (e.g. by calling ``require()``) will get activated as well,
3696 # with higher priority (replace=True).
3697 tuple(dist.activate(replace=False) for dist in working_set)
3698 add_activation_listener(
3699 lambda dist: dist.activate(replace=True),
3700 existing=False,
3701 )
3702 working_set.entries = []
3703 # match order
3704 list(map(working_set.add_entry, sys.path))
3705 globals().update(locals())
3706
3707
3708 if TYPE_CHECKING:
3709 # All of these are set by the @_call_aside methods above
3710 __resource_manager = ResourceManager() # Won't exist at runtime
3711 resource_exists = __resource_manager.resource_exists
3712 resource_isdir = __resource_manager.resource_isdir
3713 resource_filename = __resource_manager.resource_filename
3714 resource_stream = __resource_manager.resource_stream
3715 resource_string = __resource_manager.resource_string
3716 resource_listdir = __resource_manager.resource_listdir
3717 set_extraction_path = __resource_manager.set_extraction_path
3718 cleanup_resources = __resource_manager.cleanup_resources
3719
3720 working_set = WorkingSet()
3721 require = working_set.require
3722 iter_entry_points = working_set.iter_entry_points
3723 add_activation_listener = working_set.subscribe
3724 run_script = working_set.run_script
3725 run_main = run_script