database.py 50 KB

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