Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 102KB

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