__init__.py 101 KB

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