__init__.py 106 KB

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