Debian Codegraph @

debian/patches/0014_pkg_resources.patch

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