__init__.py 106 KB

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