database.py 50 KB

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