__init__.py 107 KB

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