__init__.py 105 KB

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