__init__.py 104 KB

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