You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 104 KiB

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