__init__.py 123 KB

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