__init__.py 123 KB

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