database.py 50 KB

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