__init__.py 125 KB

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