__init__.py 105 KB

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