__init__.py 106 KB

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