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

1359 lines
51 KiB

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