Debian Codegraph @

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