You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 106KB

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