__init__.py 106 KB

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