__init__.py 110 KB

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