database.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2023 The Python Software Foundation.
  4. # See LICENSE.txt and CONTRIBUTORS.txt.
  5. #
  6. """PEP 376 implementation."""
  7. from __future__ import unicode_literals
  8. import base64
  9. import codecs
  10. import contextlib
  11. import hashlib
  12. import logging
  13. import os
  14. import posixpath
  15. import sys
  16. import zipimport
  17. from . import DistlibException, resources
  18. from .compat import StringIO
  19. from .version import get_scheme, UnsupportedVersionError
  20. from .metadata import (Metadata, METADATA_FILENAME, WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME)
  21. from .util import (parse_requirement, cached_property, parse_name_and_version, read_exports, write_exports, CSVReader,
  22. CSVWriter)
  23. __all__ = [
  24. 'Distribution', 'BaseInstalledDistribution', 'InstalledDistribution', 'EggInfoDistribution', 'DistributionPath'
  25. ]
  26. logger = logging.getLogger(__name__)
  27. EXPORTS_FILENAME = 'pydist-exports.json'
  28. COMMANDS_FILENAME = 'pydist-commands.json'
  29. DIST_FILES = ('INSTALLER', METADATA_FILENAME, 'RECORD', 'REQUESTED', 'RESOURCES', EXPORTS_FILENAME, 'SHARED')
  30. DISTINFO_EXT = '.dist-info'
  31. class _Cache(object):
  32. """
  33. A simple cache mapping names and .dist-info paths to distributions
  34. """
  35. def __init__(self):
  36. """
  37. Initialise an instance. There is normally one for each DistributionPath.
  38. """
  39. self.name = {}
  40. self.path = {}
  41. self.generated = False
  42. def clear(self):
  43. """
  44. Clear the cache, setting it to its initial state.
  45. """
  46. self.name.clear()
  47. self.path.clear()
  48. self.generated = False
  49. def add(self, dist):
  50. """
  51. Add a distribution to the cache.
  52. :param dist: The distribution to add.
  53. """
  54. if dist.path not in self.path:
  55. self.path[dist.path] = dist
  56. self.name.setdefault(dist.key, []).append(dist)
  57. class DistributionPath(object):
  58. """
  59. Represents a set of distributions installed on a path (typically sys.path).
  60. """
  61. def __init__(self, path=None, include_egg=False):
  62. """
  63. Create an instance from a path, optionally including legacy (distutils/
  64. setuptools/distribute) distributions.
  65. :param path: The path to use, as a list of directories. If not specified,
  66. sys.path is used.
  67. :param include_egg: If True, this instance will look for and return legacy
  68. distributions as well as those based on PEP 376.
  69. """
  70. if path is None:
  71. path = sys.path
  72. self.path = path
  73. self._include_dist = True
  74. self._include_egg = include_egg
  75. self._cache = _Cache()
  76. self._cache_egg = _Cache()
  77. self._cache_enabled = True
  78. self._scheme = get_scheme('default')
  79. def _get_cache_enabled(self):
  80. return self._cache_enabled
  81. def _set_cache_enabled(self, value):
  82. self._cache_enabled = value
  83. cache_enabled = property(_get_cache_enabled, _set_cache_enabled)
  84. def clear_cache(self):
  85. """
  86. Clears the internal cache.
  87. """
  88. self._cache.clear()
  89. self._cache_egg.clear()
  90. def _yield_distributions(self):
  91. """
  92. Yield .dist-info and/or .egg(-info) distributions.
  93. """
  94. # We need to check if we've seen some resources already, because on
  95. # some Linux systems (e.g. some Debian/Ubuntu variants) there are
  96. # symlinks which alias other files in the environment.
  97. seen = set()
  98. for path in self.path:
  99. finder = resources.finder_for_path(path)
  100. if finder is None:
  101. continue
  102. r = finder.find('')
  103. if not r or not r.is_container:
  104. continue
  105. rset = sorted(r.resources)
  106. for entry in rset:
  107. r = finder.find(entry)
  108. if not r or r.path in seen:
  109. continue
  110. try:
  111. if self._include_dist and entry.endswith(DISTINFO_EXT):
  112. possible_filenames = [METADATA_FILENAME, WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME]
  113. for metadata_filename in possible_filenames:
  114. metadata_path = posixpath.join(entry, metadata_filename)
  115. pydist = finder.find(metadata_path)
  116. if pydist:
  117. break
  118. else:
  119. continue
  120. with contextlib.closing(pydist.as_stream()) as stream:
  121. metadata = Metadata(fileobj=stream, scheme='legacy')
  122. logger.debug('Found %s', r.path)
  123. seen.add(r.path)
  124. yield new_dist_class(r.path, metadata=metadata, env=self)
  125. elif self._include_egg and entry.endswith(('.egg-info', '.egg')):
  126. logger.debug('Found %s', r.path)
  127. seen.add(r.path)
  128. yield old_dist_class(r.path, self)
  129. except Exception as e:
  130. msg = 'Unable to read distribution at %s, perhaps due to bad metadata: %s'
  131. logger.warning(msg, r.path, e)
  132. import warnings
  133. warnings.warn(msg % (r.path, e), stacklevel=2)
  134. def _generate_cache(self):
  135. """
  136. Scan the path for distributions and populate the cache with
  137. those that are found.
  138. """
  139. gen_dist = not self._cache.generated
  140. gen_egg = self._include_egg and not self._cache_egg.generated
  141. if gen_dist or gen_egg:
  142. for dist in self._yield_distributions():
  143. if isinstance(dist, InstalledDistribution):
  144. self._cache.add(dist)
  145. else:
  146. self._cache_egg.add(dist)
  147. if gen_dist:
  148. self._cache.generated = True
  149. if gen_egg:
  150. self._cache_egg.generated = True
  151. @classmethod
  152. def distinfo_dirname(cls, name, version):
  153. """
  154. The *name* and *version* parameters are converted into their
  155. filename-escaped form, i.e. any ``'-'`` characters are replaced
  156. with ``'_'`` other than the one in ``'dist-info'`` and the one
  157. separating the name from the version number.
  158. :parameter name: is converted to a standard distribution name by replacing
  159. any runs of non- alphanumeric characters with a single
  160. ``'-'``.
  161. :type name: string
  162. :parameter version: is converted to a standard version string. Spaces
  163. become dots, and all other non-alphanumeric characters
  164. (except dots) become dashes, with runs of multiple
  165. dashes condensed to a single dash.
  166. :type version: string
  167. :returns: directory name
  168. :rtype: string"""
  169. name = name.replace('-', '_')
  170. return '-'.join([name, version]) + DISTINFO_EXT
  171. def get_distributions(self):
  172. """
  173. Provides an iterator that looks for distributions and returns
  174. :class:`InstalledDistribution` or
  175. :class:`EggInfoDistribution` instances for each one of them.
  176. :rtype: iterator of :class:`InstalledDistribution` and
  177. :class:`EggInfoDistribution` instances
  178. """
  179. if not self._cache_enabled:
  180. for dist in self._yield_distributions():
  181. yield dist
  182. else:
  183. self._generate_cache()
  184. for dist in self._cache.path.values():
  185. yield dist
  186. if self._include_egg:
  187. for dist in self._cache_egg.path.values():
  188. yield dist
  189. def get_distribution(self, name):
  190. """
  191. Looks for a named distribution on the path.
  192. This function only returns the first result found, as no more than one
  193. value is expected. If nothing is found, ``None`` is returned.
  194. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`
  195. or ``None``
  196. """
  197. result = None
  198. name = name.lower()
  199. if not self._cache_enabled:
  200. for dist in self._yield_distributions():
  201. if dist.key == name:
  202. result = dist
  203. break
  204. else:
  205. self._generate_cache()
  206. if name in self._cache.name:
  207. result = self._cache.name[name][0]
  208. elif self._include_egg and name in self._cache_egg.name:
  209. result = self._cache_egg.name[name][0]
  210. return result
  211. def provides_distribution(self, name, version=None):
  212. """
  213. Iterates over all distributions to find which distributions provide *name*.
  214. If a *version* is provided, it will be used to filter the results.
  215. This function only returns the first result found, since no more than
  216. one values are expected. If the directory is not found, returns ``None``.
  217. :parameter version: a version specifier that indicates the version
  218. required, conforming to the format in ``PEP-345``
  219. :type name: string
  220. :type version: string
  221. """
  222. matcher = None
  223. if version is not None:
  224. try:
  225. matcher = self._scheme.matcher('%s (%s)' % (name, version))
  226. except ValueError:
  227. raise DistlibException('invalid name or version: %r, %r' % (name, version))
  228. for dist in self.get_distributions():
  229. # We hit a problem on Travis where enum34 was installed and doesn't
  230. # have a provides attribute ...
  231. if not hasattr(dist, 'provides'):
  232. logger.debug('No "provides": %s', dist)
  233. else:
  234. provided = dist.provides
  235. for p in provided:
  236. p_name, p_ver = parse_name_and_version(p)
  237. if matcher is None:
  238. if p_name == name:
  239. yield dist
  240. break
  241. else:
  242. if p_name == name and matcher.match(p_ver):
  243. yield dist
  244. break
  245. def get_file_path(self, name, relative_path):
  246. """
  247. Return the path to a resource file.
  248. """
  249. dist = self.get_distribution(name)
  250. if dist is None:
  251. raise LookupError('no distribution named %r found' % name)
  252. return dist.get_resource_path(relative_path)
  253. def get_exported_entries(self, category, name=None):
  254. """
  255. Return all of the exported entries in a particular category.
  256. :param category: The category to search for entries.
  257. :param name: If specified, only entries with that name are returned.
  258. """
  259. for dist in self.get_distributions():
  260. r = dist.exports
  261. if category in r:
  262. d = r[category]
  263. if name is not None:
  264. if name in d:
  265. yield d[name]
  266. else:
  267. for v in d.values():
  268. yield v
  269. class Distribution(object):
  270. """
  271. A base class for distributions, whether installed or from indexes.
  272. Either way, it must have some metadata, so that's all that's needed
  273. for construction.
  274. """
  275. build_time_dependency = False
  276. """
  277. Set to True if it's known to be only a build-time dependency (i.e.
  278. not needed after installation).
  279. """
  280. requested = False
  281. """A boolean that indicates whether the ``REQUESTED`` metadata file is
  282. present (in other words, whether the package was installed by user
  283. request or it was installed as a dependency)."""
  284. def __init__(self, metadata):
  285. """
  286. Initialise an instance.
  287. :param metadata: The instance of :class:`Metadata` describing this
  288. distribution.
  289. """
  290. self.metadata = metadata
  291. self.name = metadata.name
  292. self.key = self.name.lower() # for case-insensitive comparisons
  293. self.version = metadata.version
  294. self.locator = None
  295. self.digest = None
  296. self.extras = None # additional features requested
  297. self.context = None # environment marker overrides
  298. self.download_urls = set()
  299. self.digests = {}
  300. @property
  301. def source_url(self):
  302. """
  303. The source archive download URL for this distribution.
  304. """
  305. return self.metadata.source_url
  306. download_url = source_url # Backward compatibility
  307. @property
  308. def name_and_version(self):
  309. """
  310. A utility property which displays the name and version in parentheses.
  311. """
  312. return '%s (%s)' % (self.name, self.version)
  313. @property
  314. def provides(self):
  315. """
  316. A set of distribution names and versions provided by this distribution.
  317. :return: A set of "name (version)" strings.
  318. """
  319. plist = self.metadata.provides
  320. s = '%s (%s)' % (self.name, self.version)
  321. if s not in plist:
  322. plist.append(s)
  323. return plist
  324. def _get_requirements(self, req_attr):
  325. md = self.metadata
  326. reqts = getattr(md, req_attr)
  327. logger.debug('%s: got requirements %r from metadata: %r', self.name, req_attr, reqts)
  328. return set(md.get_requirements(reqts, extras=self.extras, env=self.context))
  329. @property
  330. def run_requires(self):
  331. return self._get_requirements('run_requires')
  332. @property
  333. def meta_requires(self):
  334. return self._get_requirements('meta_requires')
  335. @property
  336. def build_requires(self):
  337. return self._get_requirements('build_requires')
  338. @property
  339. def test_requires(self):
  340. return self._get_requirements('test_requires')
  341. @property
  342. def dev_requires(self):
  343. return self._get_requirements('dev_requires')
  344. def matches_requirement(self, req):
  345. """
  346. Say if this instance matches (fulfills) a requirement.
  347. :param req: The requirement to match.
  348. :rtype req: str
  349. :return: True if it matches, else False.
  350. """
  351. # Requirement may contain extras - parse to lose those
  352. # from what's passed to the matcher
  353. r = parse_requirement(req)
  354. scheme = get_scheme(self.metadata.scheme)
  355. try:
  356. matcher = scheme.matcher(r.requirement)
  357. except UnsupportedVersionError:
  358. # XXX compat-mode if cannot read the version
  359. logger.warning('could not read version %r - using name only', req)
  360. name = req.split()[0]
  361. matcher = scheme.matcher(name)
  362. name = matcher.key # case-insensitive
  363. result = False
  364. for p in self.provides:
  365. p_name, p_ver = parse_name_and_version(p)
  366. if p_name != name:
  367. continue
  368. try:
  369. result = matcher.match(p_ver)
  370. break
  371. except UnsupportedVersionError:
  372. pass
  373. return result
  374. def __repr__(self):
  375. """
  376. Return a textual representation of this instance,
  377. """
  378. if self.source_url:
  379. suffix = ' [%s]' % self.source_url
  380. else:
  381. suffix = ''
  382. return '<Distribution %s (%s)%s>' % (self.name, self.version, suffix)
  383. def __eq__(self, other):
  384. """
  385. See if this distribution is the same as another.
  386. :param other: The distribution to compare with. To be equal to one
  387. another. distributions must have the same type, name,
  388. version and source_url.
  389. :return: True if it is the same, else False.
  390. """
  391. if type(other) is not type(self):
  392. result = False
  393. else:
  394. result = (self.name == other.name and self.version == other.version and self.source_url == other.source_url)
  395. return result
  396. def __hash__(self):
  397. """
  398. Compute hash in a way which matches the equality test.
  399. """
  400. return hash(self.name) + hash(self.version) + hash(self.source_url)
  401. class BaseInstalledDistribution(Distribution):
  402. """
  403. This is the base class for installed distributions (whether PEP 376 or
  404. legacy).
  405. """
  406. hasher = None
  407. def __init__(self, metadata, path, env=None):
  408. """
  409. Initialise an instance.
  410. :param metadata: An instance of :class:`Metadata` which describes the
  411. distribution. This will normally have been initialised
  412. from a metadata file in the ``path``.
  413. :param path: The path of the ``.dist-info`` or ``.egg-info``
  414. directory for the distribution.
  415. :param env: This is normally the :class:`DistributionPath`
  416. instance where this distribution was found.
  417. """
  418. super(BaseInstalledDistribution, self).__init__(metadata)
  419. self.path = path
  420. self.dist_path = env
  421. def get_hash(self, data, hasher=None):
  422. """
  423. Get the hash of some data, using a particular hash algorithm, if
  424. specified.
  425. :param data: The data to be hashed.
  426. :type data: bytes
  427. :param hasher: The name of a hash implementation, supported by hashlib,
  428. or ``None``. Examples of valid values are ``'sha1'``,
  429. ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and
  430. ``'sha512'``. If no hasher is specified, the ``hasher``
  431. attribute of the :class:`InstalledDistribution` instance
  432. is used. If the hasher is determined to be ``None``, MD5
  433. is used as the hashing algorithm.
  434. :returns: The hash of the data. If a hasher was explicitly specified,
  435. the returned hash will be prefixed with the specified hasher
  436. followed by '='.
  437. :rtype: str
  438. """
  439. if hasher is None:
  440. hasher = self.hasher
  441. if hasher is None:
  442. hasher = hashlib.md5
  443. prefix = ''
  444. else:
  445. hasher = getattr(hashlib, hasher)
  446. prefix = '%s=' % self.hasher
  447. digest = hasher(data).digest()
  448. digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
  449. return '%s%s' % (prefix, digest)
  450. class InstalledDistribution(BaseInstalledDistribution):
  451. """
  452. Created with the *path* of the ``.dist-info`` directory provided to the
  453. constructor. It reads the metadata contained in ``pydist.json`` when it is
  454. instantiated., or uses a passed in Metadata instance (useful for when
  455. dry-run mode is being used).
  456. """
  457. hasher = 'sha256'
  458. def __init__(self, path, metadata=None, env=None):
  459. self.modules = []
  460. self.finder = finder = resources.finder_for_path(path)
  461. if finder is None:
  462. raise ValueError('finder unavailable for %s' % path)
  463. if env and env._cache_enabled and path in env._cache.path:
  464. metadata = env._cache.path[path].metadata
  465. elif metadata is None:
  466. r = finder.find(METADATA_FILENAME)
  467. # Temporary - for Wheel 0.23 support
  468. if r is None:
  469. r = finder.find(WHEEL_METADATA_FILENAME)
  470. # Temporary - for legacy support
  471. if r is None:
  472. r = finder.find(LEGACY_METADATA_FILENAME)
  473. if r is None:
  474. raise ValueError('no %s found in %s' % (METADATA_FILENAME, path))
  475. with contextlib.closing(r.as_stream()) as stream:
  476. metadata = Metadata(fileobj=stream, scheme='legacy')
  477. super(InstalledDistribution, self).__init__(metadata, path, env)
  478. if env and env._cache_enabled:
  479. env._cache.add(self)
  480. r = finder.find('REQUESTED')
  481. self.requested = r is not None
  482. p = os.path.join(path, 'top_level.txt')
  483. if os.path.exists(p):
  484. with open(p, 'rb') as f:
  485. data = f.read().decode('utf-8')
  486. self.modules = data.splitlines()
  487. def __repr__(self):
  488. return '<InstalledDistribution %r %s at %r>' % (self.name, self.version, self.path)
  489. def __str__(self):
  490. return "%s %s" % (self.name, self.version)
  491. def _get_records(self):
  492. """
  493. Get the list of installed files for the distribution
  494. :return: A list of tuples of path, hash and size. Note that hash and
  495. size might be ``None`` for some entries. The path is exactly
  496. as stored in the file (which is as in PEP 376).
  497. """
  498. results = []
  499. r = self.get_distinfo_resource('RECORD')
  500. with contextlib.closing(r.as_stream()) as stream:
  501. with CSVReader(stream=stream) as record_reader:
  502. # Base location is parent dir of .dist-info dir
  503. # base_location = os.path.dirname(self.path)
  504. # base_location = os.path.abspath(base_location)
  505. for row in record_reader:
  506. missing = [None for i in range(len(row), 3)]
  507. path, checksum, size = row + missing
  508. # if not os.path.isabs(path):
  509. # path = path.replace('/', os.sep)
  510. # path = os.path.join(base_location, path)
  511. results.append((path, checksum, size))
  512. return results
  513. @cached_property
  514. def exports(self):
  515. """
  516. Return the information exported by this distribution.
  517. :return: A dictionary of exports, mapping an export category to a dict
  518. of :class:`ExportEntry` instances describing the individual
  519. export entries, and keyed by name.
  520. """
  521. result = {}
  522. r = self.get_distinfo_resource(EXPORTS_FILENAME)
  523. if r:
  524. result = self.read_exports()
  525. return result
  526. def read_exports(self):
  527. """
  528. Read exports data from a file in .ini format.
  529. :return: A dictionary of exports, mapping an export category to a list
  530. of :class:`ExportEntry` instances describing the individual
  531. export entries.
  532. """
  533. result = {}
  534. r = self.get_distinfo_resource(EXPORTS_FILENAME)
  535. if r:
  536. with contextlib.closing(r.as_stream()) as stream:
  537. result = read_exports(stream)
  538. return result
  539. def write_exports(self, exports):
  540. """
  541. Write a dictionary of exports to a file in .ini format.
  542. :param exports: A dictionary of exports, mapping an export category to
  543. a list of :class:`ExportEntry` instances describing the
  544. individual export entries.
  545. """
  546. rf = self.get_distinfo_file(EXPORTS_FILENAME)
  547. with open(rf, 'w') as f:
  548. write_exports(exports, f)
  549. def get_resource_path(self, relative_path):
  550. """
  551. NOTE: This API may change in the future.
  552. Return the absolute path to a resource file with the given relative
  553. path.
  554. :param relative_path: The path, relative to .dist-info, of the resource
  555. of interest.
  556. :return: The absolute path where the resource is to be found.
  557. """
  558. r = self.get_distinfo_resource('RESOURCES')
  559. with contextlib.closing(r.as_stream()) as stream:
  560. with CSVReader(stream=stream) as resources_reader:
  561. for relative, destination in resources_reader:
  562. if relative == relative_path:
  563. return destination
  564. raise KeyError('no resource file with relative path %r '
  565. 'is installed' % relative_path)
  566. def list_installed_files(self):
  567. """
  568. Iterates over the ``RECORD`` entries and returns a tuple
  569. ``(path, hash, size)`` for each line.
  570. :returns: iterator of (path, hash, size)
  571. """
  572. for result in self._get_records():
  573. yield result
  574. def write_installed_files(self, paths, prefix, dry_run=False):
  575. """
  576. Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any
  577. existing ``RECORD`` file is silently overwritten.
  578. prefix is used to determine when to write absolute paths.
  579. """
  580. prefix = os.path.join(prefix, '')
  581. base = os.path.dirname(self.path)
  582. base_under_prefix = base.startswith(prefix)
  583. base = os.path.join(base, '')
  584. record_path = self.get_distinfo_file('RECORD')
  585. logger.info('creating %s', record_path)
  586. if dry_run:
  587. return None
  588. with CSVWriter(record_path) as writer:
  589. for path in paths:
  590. if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')):
  591. # do not put size and hash, as in PEP-376
  592. hash_value = size = ''
  593. else:
  594. size = '%d' % os.path.getsize(path)
  595. with open(path, 'rb') as fp:
  596. hash_value = self.get_hash(fp.read())
  597. if path.startswith(base) or (base_under_prefix and path.startswith(prefix)):
  598. path = os.path.relpath(path, base)
  599. writer.writerow((path, hash_value, size))
  600. # add the RECORD file itself
  601. if record_path.startswith(base):
  602. record_path = os.path.relpath(record_path, base)
  603. writer.writerow((record_path, '', ''))
  604. return record_path
  605. def check_installed_files(self):
  606. """
  607. Checks that the hashes and sizes of the files in ``RECORD`` are
  608. matched by the files themselves. Returns a (possibly empty) list of
  609. mismatches. Each entry in the mismatch list will be a tuple consisting
  610. of the path, 'exists', 'size' or 'hash' according to what didn't match
  611. (existence is checked first, then size, then hash), the expected
  612. value and the actual value.
  613. """
  614. mismatches = []
  615. base = os.path.dirname(self.path)
  616. record_path = self.get_distinfo_file('RECORD')
  617. for path, hash_value, size in self.list_installed_files():
  618. if not os.path.isabs(path):
  619. path = os.path.join(base, path)
  620. if path == record_path:
  621. continue
  622. if not os.path.exists(path):
  623. mismatches.append((path, 'exists', True, False))
  624. elif os.path.isfile(path):
  625. actual_size = str(os.path.getsize(path))
  626. if size and actual_size != size:
  627. mismatches.append((path, 'size', size, actual_size))
  628. elif hash_value:
  629. if '=' in hash_value:
  630. hasher = hash_value.split('=', 1)[0]
  631. else:
  632. hasher = None
  633. with open(path, 'rb') as f:
  634. actual_hash = self.get_hash(f.read(), hasher)
  635. if actual_hash != hash_value:
  636. mismatches.append((path, 'hash', hash_value, actual_hash))
  637. return mismatches
  638. @cached_property
  639. def shared_locations(self):
  640. """
  641. A dictionary of shared locations whose keys are in the set 'prefix',
  642. 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
  643. The corresponding value is the absolute path of that category for
  644. this distribution, and takes into account any paths selected by the
  645. user at installation time (e.g. via command-line arguments). In the
  646. case of the 'namespace' key, this would be a list of absolute paths
  647. for the roots of namespace packages in this distribution.
  648. The first time this property is accessed, the relevant information is
  649. read from the SHARED file in the .dist-info directory.
  650. """
  651. result = {}
  652. shared_path = os.path.join(self.path, 'SHARED')
  653. if os.path.isfile(shared_path):
  654. with codecs.open(shared_path, 'r', encoding='utf-8') as f:
  655. lines = f.read().splitlines()
  656. for line in lines:
  657. key, value = line.split('=', 1)
  658. if key == 'namespace':
  659. result.setdefault(key, []).append(value)
  660. else:
  661. result[key] = value
  662. return result
  663. def write_shared_locations(self, paths, dry_run=False):
  664. """
  665. Write shared location information to the SHARED file in .dist-info.
  666. :param paths: A dictionary as described in the documentation for
  667. :meth:`shared_locations`.
  668. :param dry_run: If True, the action is logged but no file is actually
  669. written.
  670. :return: The path of the file written to.
  671. """
  672. shared_path = os.path.join(self.path, 'SHARED')
  673. logger.info('creating %s', shared_path)
  674. if dry_run:
  675. return None
  676. lines = []
  677. for key in ('prefix', 'lib', 'headers', 'scripts', 'data'):
  678. path = paths[key]
  679. if os.path.isdir(paths[key]):
  680. lines.append('%s=%s' % (key, path))
  681. for ns in paths.get('namespace', ()):
  682. lines.append('namespace=%s' % ns)
  683. with codecs.open(shared_path, 'w', encoding='utf-8') as f:
  684. f.write('\n'.join(lines))
  685. return shared_path
  686. def get_distinfo_resource(self, path):
  687. if path not in DIST_FILES:
  688. raise DistlibException('invalid path for a dist-info file: '
  689. '%r at %r' % (path, self.path))
  690. finder = resources.finder_for_path(self.path)
  691. if finder is None:
  692. raise DistlibException('Unable to get a finder for %s' % self.path)
  693. return finder.find(path)
  694. def get_distinfo_file(self, path):
  695. """
  696. Returns a path located under the ``.dist-info`` directory. Returns a
  697. string representing the path.
  698. :parameter path: a ``'/'``-separated path relative to the
  699. ``.dist-info`` directory or an absolute path;
  700. If *path* is an absolute path and doesn't start
  701. with the ``.dist-info`` directory path,
  702. a :class:`DistlibException` is raised
  703. :type path: str
  704. :rtype: str
  705. """
  706. # Check if it is an absolute path # XXX use relpath, add tests
  707. if path.find(os.sep) >= 0:
  708. # it's an absolute path?
  709. distinfo_dirname, path = path.split(os.sep)[-2:]
  710. if distinfo_dirname != self.path.split(os.sep)[-1]:
  711. raise DistlibException('dist-info file %r does not belong to the %r %s '
  712. 'distribution' % (path, self.name, self.version))
  713. # The file must be relative
  714. if path not in DIST_FILES:
  715. raise DistlibException('invalid path for a dist-info file: '
  716. '%r at %r' % (path, self.path))
  717. return os.path.join(self.path, path)
  718. def list_distinfo_files(self):
  719. """
  720. Iterates over the ``RECORD`` entries and returns paths for each line if
  721. the path is pointing to a file located in the ``.dist-info`` directory
  722. or one of its subdirectories.
  723. :returns: iterator of paths
  724. """
  725. base = os.path.dirname(self.path)
  726. for path, checksum, size in self._get_records():
  727. # XXX add separator or use real relpath algo
  728. if not os.path.isabs(path):
  729. path = os.path.join(base, path)
  730. if path.startswith(self.path):
  731. yield path
  732. def __eq__(self, other):
  733. return (isinstance(other, InstalledDistribution) and self.path == other.path)
  734. # See http://docs.python.org/reference/datamodel#object.__hash__
  735. __hash__ = object.__hash__
  736. class EggInfoDistribution(BaseInstalledDistribution):
  737. """Created with the *path* of the ``.egg-info`` directory or file provided
  738. to the constructor. It reads the metadata contained in the file itself, or
  739. if the given path happens to be a directory, the metadata is read from the
  740. file ``PKG-INFO`` under that directory."""
  741. requested = True # as we have no way of knowing, assume it was
  742. shared_locations = {}
  743. def __init__(self, path, env=None):
  744. def set_name_and_version(s, n, v):
  745. s.name = n
  746. s.key = n.lower() # for case-insensitive comparisons
  747. s.version = v
  748. self.path = path
  749. self.dist_path = env
  750. if env and env._cache_enabled and path in env._cache_egg.path:
  751. metadata = env._cache_egg.path[path].metadata
  752. set_name_and_version(self, metadata.name, metadata.version)
  753. else:
  754. metadata = self._get_metadata(path)
  755. # Need to be set before caching
  756. set_name_and_version(self, metadata.name, metadata.version)
  757. if env and env._cache_enabled:
  758. env._cache_egg.add(self)
  759. super(EggInfoDistribution, self).__init__(metadata, path, env)
  760. def _get_metadata(self, path):
  761. requires = None
  762. def parse_requires_data(data):
  763. """Create a list of dependencies from a requires.txt file.
  764. *data*: the contents of a setuptools-produced requires.txt file.
  765. """
  766. reqs = []
  767. lines = data.splitlines()
  768. for line in lines:
  769. line = line.strip()
  770. # sectioned files have bare newlines (separating sections)
  771. if not line: # pragma: no cover
  772. continue
  773. if line.startswith('['): # pragma: no cover
  774. logger.warning('Unexpected line: quitting requirement scan: %r', line)
  775. break
  776. r = parse_requirement(line)
  777. if not r: # pragma: no cover
  778. logger.warning('Not recognised as a requirement: %r', line)
  779. continue
  780. if r.extras: # pragma: no cover
  781. logger.warning('extra requirements in requires.txt are '
  782. 'not supported')
  783. if not r.constraints:
  784. reqs.append(r.name)
  785. else:
  786. cons = ', '.join('%s%s' % c for c in r.constraints)
  787. reqs.append('%s (%s)' % (r.name, cons))
  788. return reqs
  789. def parse_requires_path(req_path):
  790. """Create a list of dependencies from a requires.txt file.
  791. *req_path*: the path to a setuptools-produced requires.txt file.
  792. """
  793. reqs = []
  794. try:
  795. with codecs.open(req_path, 'r', 'utf-8') as fp:
  796. reqs = parse_requires_data(fp.read())
  797. except IOError:
  798. pass
  799. return reqs
  800. tl_path = tl_data = None
  801. if path.endswith('.egg'):
  802. if os.path.isdir(path):
  803. p = os.path.join(path, 'EGG-INFO')
  804. meta_path = os.path.join(p, 'PKG-INFO')
  805. metadata = Metadata(path=meta_path, scheme='legacy')
  806. req_path = os.path.join(p, 'requires.txt')
  807. tl_path = os.path.join(p, 'top_level.txt')
  808. requires = parse_requires_path(req_path)
  809. else:
  810. # FIXME handle the case where zipfile is not available
  811. zipf = zipimport.zipimporter(path)
  812. fileobj = StringIO(zipf.get_data('EGG-INFO/PKG-INFO').decode('utf8'))
  813. metadata = Metadata(fileobj=fileobj, scheme='legacy')
  814. try:
  815. data = zipf.get_data('EGG-INFO/requires.txt')
  816. tl_data = zipf.get_data('EGG-INFO/top_level.txt').decode('utf-8')
  817. requires = parse_requires_data(data.decode('utf-8'))
  818. except IOError:
  819. requires = None
  820. elif path.endswith('.egg-info'):
  821. if os.path.isdir(path):
  822. req_path = os.path.join(path, 'requires.txt')
  823. requires = parse_requires_path(req_path)
  824. path = os.path.join(path, 'PKG-INFO')
  825. tl_path = os.path.join(path, 'top_level.txt')
  826. metadata = Metadata(path=path, scheme='legacy')
  827. else:
  828. raise DistlibException('path must end with .egg-info or .egg, '
  829. 'got %r' % path)
  830. if requires:
  831. metadata.add_requirements(requires)
  832. # look for top-level modules in top_level.txt, if present
  833. if tl_data is None:
  834. if tl_path is not None and os.path.exists(tl_path):
  835. with open(tl_path, 'rb') as f:
  836. tl_data = f.read().decode('utf-8')
  837. if not tl_data:
  838. tl_data = []
  839. else:
  840. tl_data = tl_data.splitlines()
  841. self.modules = tl_data
  842. return metadata
  843. def __repr__(self):
  844. return '<EggInfoDistribution %r %s at %r>' % (self.name, self.version, self.path)
  845. def __str__(self):
  846. return "%s %s" % (self.name, self.version)
  847. def check_installed_files(self):
  848. """
  849. Checks that the hashes and sizes of the files in ``RECORD`` are
  850. matched by the files themselves. Returns a (possibly empty) list of
  851. mismatches. Each entry in the mismatch list will be a tuple consisting
  852. of the path, 'exists', 'size' or 'hash' according to what didn't match
  853. (existence is checked first, then size, then hash), the expected
  854. value and the actual value.
  855. """
  856. mismatches = []
  857. record_path = os.path.join(self.path, 'installed-files.txt')
  858. if os.path.exists(record_path):
  859. for path, _, _ in self.list_installed_files():
  860. if path == record_path:
  861. continue
  862. if not os.path.exists(path):
  863. mismatches.append((path, 'exists', True, False))
  864. return mismatches
  865. def list_installed_files(self):
  866. """
  867. Iterates over the ``installed-files.txt`` entries and returns a tuple
  868. ``(path, hash, size)`` for each line.
  869. :returns: a list of (path, hash, size)
  870. """
  871. def _md5(path):
  872. f = open(path, 'rb')
  873. try:
  874. content = f.read()
  875. finally:
  876. f.close()
  877. return hashlib.md5(content).hexdigest()
  878. def _size(path):
  879. return os.stat(path).st_size
  880. record_path = os.path.join(self.path, 'installed-files.txt')
  881. result = []
  882. if os.path.exists(record_path):
  883. with codecs.open(record_path, 'r', encoding='utf-8') as f:
  884. for line in f:
  885. line = line.strip()
  886. p = os.path.normpath(os.path.join(self.path, line))
  887. # "./" is present as a marker between installed files
  888. # and installation metadata files
  889. if not os.path.exists(p):
  890. logger.warning('Non-existent file: %s', p)
  891. if p.endswith(('.pyc', '.pyo')):
  892. continue
  893. # otherwise fall through and fail
  894. if not os.path.isdir(p):
  895. result.append((p, _md5(p), _size(p)))
  896. result.append((record_path, None, None))
  897. return result
  898. def list_distinfo_files(self, absolute=False):
  899. """
  900. Iterates over the ``installed-files.txt`` entries and returns paths for
  901. each line if the path is pointing to a file located in the
  902. ``.egg-info`` directory or one of its subdirectories.
  903. :parameter absolute: If *absolute* is ``True``, each returned path is
  904. transformed into a local absolute path. Otherwise the
  905. raw value from ``installed-files.txt`` is returned.
  906. :type absolute: boolean
  907. :returns: iterator of paths
  908. """
  909. record_path = os.path.join(self.path, 'installed-files.txt')
  910. if os.path.exists(record_path):
  911. skip = True
  912. with codecs.open(record_path, 'r', encoding='utf-8') as f:
  913. for line in f:
  914. line = line.strip()
  915. if line == './':
  916. skip = False
  917. continue
  918. if not skip:
  919. p = os.path.normpath(os.path.join(self.path, line))
  920. if p.startswith(self.path):
  921. if absolute:
  922. yield p
  923. else:
  924. yield line
  925. def __eq__(self, other):
  926. return (isinstance(other, EggInfoDistribution) and self.path == other.path)
  927. # See http://docs.python.org/reference/datamodel#object.__hash__
  928. __hash__ = object.__hash__
  929. new_dist_class = InstalledDistribution
  930. old_dist_class = EggInfoDistribution
  931. class DependencyGraph(object):
  932. """
  933. Represents a dependency graph between distributions.
  934. The dependency relationships are stored in an ``adjacency_list`` that maps
  935. distributions to a list of ``(other, label)`` tuples where ``other``
  936. is a distribution and the edge is labeled with ``label`` (i.e. the version
  937. specifier, if such was provided). Also, for more efficient traversal, for
  938. every distribution ``x``, a list of predecessors is kept in
  939. ``reverse_list[x]``. An edge from distribution ``a`` to
  940. distribution ``b`` means that ``a`` depends on ``b``. If any missing
  941. dependencies are found, they are stored in ``missing``, which is a
  942. dictionary that maps distributions to a list of requirements that were not
  943. provided by any other distributions.
  944. """
  945. def __init__(self):
  946. self.adjacency_list = {}
  947. self.reverse_list = {}
  948. self.missing = {}
  949. def add_distribution(self, distribution):
  950. """Add the *distribution* to the graph.
  951. :type distribution: :class:`distutils2.database.InstalledDistribution`
  952. or :class:`distutils2.database.EggInfoDistribution`
  953. """
  954. self.adjacency_list[distribution] = []
  955. self.reverse_list[distribution] = []
  956. # self.missing[distribution] = []
  957. def add_edge(self, x, y, label=None):
  958. """Add an edge from distribution *x* to distribution *y* with the given
  959. *label*.
  960. :type x: :class:`distutils2.database.InstalledDistribution` or
  961. :class:`distutils2.database.EggInfoDistribution`
  962. :type y: :class:`distutils2.database.InstalledDistribution` or
  963. :class:`distutils2.database.EggInfoDistribution`
  964. :type label: ``str`` or ``None``
  965. """
  966. self.adjacency_list[x].append((y, label))
  967. # multiple edges are allowed, so be careful
  968. if x not in self.reverse_list[y]:
  969. self.reverse_list[y].append(x)
  970. def add_missing(self, distribution, requirement):
  971. """
  972. Add a missing *requirement* for the given *distribution*.
  973. :type distribution: :class:`distutils2.database.InstalledDistribution`
  974. or :class:`distutils2.database.EggInfoDistribution`
  975. :type requirement: ``str``
  976. """
  977. logger.debug('%s missing %r', distribution, requirement)
  978. self.missing.setdefault(distribution, []).append(requirement)
  979. def _repr_dist(self, dist):
  980. return '%s %s' % (dist.name, dist.version)
  981. def repr_node(self, dist, level=1):
  982. """Prints only a subgraph"""
  983. output = [self._repr_dist(dist)]
  984. for other, label in self.adjacency_list[dist]:
  985. dist = self._repr_dist(other)
  986. if label is not None:
  987. dist = '%s [%s]' % (dist, label)
  988. output.append(' ' * level + str(dist))
  989. suboutput = self.repr_node(other, level + 1)
  990. subs = suboutput.split('\n')
  991. output.extend(subs[1:])
  992. return '\n'.join(output)
  993. def to_dot(self, f, skip_disconnected=True):
  994. """Writes a DOT output for the graph to the provided file *f*.
  995. If *skip_disconnected* is set to ``True``, then all distributions
  996. that are not dependent on any other distribution are skipped.
  997. :type f: has to support ``file``-like operations
  998. :type skip_disconnected: ``bool``
  999. """
  1000. disconnected = []
  1001. f.write("digraph dependencies {\n")
  1002. for dist, adjs in self.adjacency_list.items():
  1003. if len(adjs) == 0 and not skip_disconnected:
  1004. disconnected.append(dist)
  1005. for other, label in adjs:
  1006. if label is not None:
  1007. f.write('"%s" -> "%s" [label="%s"]\n' % (dist.name, other.name, label))
  1008. else:
  1009. f.write('"%s" -> "%s"\n' % (dist.name, other.name))
  1010. if not skip_disconnected and len(disconnected) > 0:
  1011. f.write('subgraph disconnected {\n')
  1012. f.write('label = "Disconnected"\n')
  1013. f.write('bgcolor = red\n')
  1014. for dist in disconnected:
  1015. f.write('"%s"' % dist.name)
  1016. f.write('\n')
  1017. f.write('}\n')
  1018. f.write('}\n')
  1019. def topological_sort(self):
  1020. """
  1021. Perform a topological sort of the graph.
  1022. :return: A tuple, the first element of which is a topologically sorted
  1023. list of distributions, and the second element of which is a
  1024. list of distributions that cannot be sorted because they have
  1025. circular dependencies and so form a cycle.
  1026. """
  1027. result = []
  1028. # Make a shallow copy of the adjacency list
  1029. alist = {}
  1030. for k, v in self.adjacency_list.items():
  1031. alist[k] = v[:]
  1032. while True:
  1033. # See what we can remove in this run
  1034. to_remove = []
  1035. for k, v in list(alist.items())[:]:
  1036. if not v:
  1037. to_remove.append(k)
  1038. del alist[k]
  1039. if not to_remove:
  1040. # What's left in alist (if anything) is a cycle.
  1041. break
  1042. # Remove from the adjacency list of others
  1043. for k, v in alist.items():
  1044. alist[k] = [(d, r) for d, r in v if d not in to_remove]
  1045. logger.debug('Moving to result: %s', ['%s (%s)' % (d.name, d.version) for d in to_remove])
  1046. result.extend(to_remove)
  1047. return result, list(alist.keys())
  1048. def __repr__(self):
  1049. """Representation of the graph"""
  1050. output = []
  1051. for dist, adjs in self.adjacency_list.items():
  1052. output.append(self.repr_node(dist))
  1053. return '\n'.join(output)
  1054. def make_graph(dists, scheme='default'):
  1055. """Makes a dependency graph from the given distributions.
  1056. :parameter dists: a list of distributions
  1057. :type dists: list of :class:`distutils2.database.InstalledDistribution` and
  1058. :class:`distutils2.database.EggInfoDistribution` instances
  1059. :rtype: a :class:`DependencyGraph` instance
  1060. """
  1061. scheme = get_scheme(scheme)
  1062. graph = DependencyGraph()
  1063. provided = {} # maps names to lists of (version, dist) tuples
  1064. # first, build the graph and find out what's provided
  1065. for dist in dists:
  1066. graph.add_distribution(dist)
  1067. for p in dist.provides:
  1068. name, version = parse_name_and_version(p)
  1069. logger.debug('Add to provided: %s, %s, %s', name, version, dist)
  1070. provided.setdefault(name, []).append((version, dist))
  1071. # now make the edges
  1072. for dist in dists:
  1073. requires = (dist.run_requires | dist.meta_requires | dist.build_requires | dist.dev_requires)
  1074. for req in requires:
  1075. try:
  1076. matcher = scheme.matcher(req)
  1077. except UnsupportedVersionError:
  1078. # XXX compat-mode if cannot read the version
  1079. logger.warning('could not read version %r - using name only', req)
  1080. name = req.split()[0]
  1081. matcher = scheme.matcher(name)
  1082. name = matcher.key # case-insensitive
  1083. matched = False
  1084. if name in provided:
  1085. for version, provider in provided[name]:
  1086. try:
  1087. match = matcher.match(version)
  1088. except UnsupportedVersionError:
  1089. match = False
  1090. if match:
  1091. graph.add_edge(dist, provider, req)
  1092. matched = True
  1093. break
  1094. if not matched:
  1095. graph.add_missing(dist, req)
  1096. return graph
  1097. def get_dependent_dists(dists, dist):
  1098. """Recursively generate a list of distributions from *dists* that are
  1099. dependent on *dist*.
  1100. :param dists: a list of distributions
  1101. :param dist: a distribution, member of *dists* for which we are interested
  1102. """
  1103. if dist not in dists:
  1104. raise DistlibException('given distribution %r is not a member '
  1105. 'of the list' % dist.name)
  1106. graph = make_graph(dists)
  1107. dep = [dist] # dependent distributions
  1108. todo = graph.reverse_list[dist] # list of nodes we should inspect
  1109. while todo:
  1110. d = todo.pop()
  1111. dep.append(d)
  1112. for succ in graph.reverse_list[d]:
  1113. if succ not in dep:
  1114. todo.append(succ)
  1115. dep.pop(0) # remove dist from dep, was there to prevent infinite loops
  1116. return dep
  1117. def get_required_dists(dists, dist):
  1118. """Recursively generate a list of distributions from *dists* that are
  1119. required by *dist*.
  1120. :param dists: a list of distributions
  1121. :param dist: a distribution, member of *dists* for which we are interested
  1122. in finding the dependencies.
  1123. """
  1124. if dist not in dists:
  1125. raise DistlibException('given distribution %r is not a member '
  1126. 'of the list' % dist.name)
  1127. graph = make_graph(dists)
  1128. req = set() # required distributions
  1129. todo = graph.adjacency_list[dist] # list of nodes we should inspect
  1130. seen = set(t[0] for t in todo) # already added to todo
  1131. while todo:
  1132. d = todo.pop()[0]
  1133. req.add(d)
  1134. pred_list = graph.adjacency_list[d]
  1135. for pred in pred_list:
  1136. d = pred[0]
  1137. if d not in req and d not in seen:
  1138. seen.add(d)
  1139. todo.append(pred)
  1140. return req
  1141. def make_dist(name, version, **kwargs):
  1142. """
  1143. A convenience method for making a dist given just a name and version.
  1144. """
  1145. summary = kwargs.pop('summary', 'Placeholder for summary')
  1146. md = Metadata(**kwargs)
  1147. md.name = name
  1148. md.version = version
  1149. md.summary = summary or 'Placeholder for summary'
  1150. return Distribution(md)