metadata.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. import io
  2. import os
  3. import re
  4. import abc
  5. import csv
  6. import sys
  7. import email
  8. import pathlib
  9. import zipfile
  10. import operator
  11. import functools
  12. import itertools
  13. import posixpath
  14. import collections
  15. from configparser import ConfigParser
  16. from contextlib import suppress
  17. from importlib import import_module
  18. from importlib.abc import MetaPathFinder
  19. from itertools import starmap
  20. __all__ = [
  21. 'Distribution',
  22. 'DistributionFinder',
  23. 'PackageNotFoundError',
  24. 'distribution',
  25. 'distributions',
  26. 'entry_points',
  27. 'files',
  28. 'metadata',
  29. 'requires',
  30. 'version',
  31. ]
  32. class PackageNotFoundError(ModuleNotFoundError):
  33. """The package was not found."""
  34. class EntryPoint(
  35. collections.namedtuple('EntryPointBase', 'name value group')):
  36. """An entry point as defined by Python packaging conventions.
  37. See `the packaging docs on entry points
  38. <https://packaging.python.org/specifications/entry-points/>`_
  39. for more information.
  40. """
  41. pattern = re.compile(
  42. r'(?P<module>[\w.]+)\s*'
  43. r'(:\s*(?P<attr>[\w.]+))?\s*'
  44. r'(?P<extras>\[.*\])?\s*$'
  45. )
  46. """
  47. A regular expression describing the syntax for an entry point,
  48. which might look like:
  49. - module
  50. - package.module
  51. - package.module:attribute
  52. - package.module:object.attribute
  53. - package.module:attr [extra1, extra2]
  54. Other combinations are possible as well.
  55. The expression is lenient about whitespace around the ':',
  56. following the attr, and following any extras.
  57. """
  58. def load(self):
  59. """Load the entry point from its definition. If only a module
  60. is indicated by the value, return that module. Otherwise,
  61. return the named object.
  62. """
  63. match = self.pattern.match(self.value)
  64. module = import_module(match.group('module'))
  65. attrs = filter(None, (match.group('attr') or '').split('.'))
  66. return functools.reduce(getattr, attrs, module)
  67. @property
  68. def module(self):
  69. match = self.pattern.match(self.value)
  70. return match.group('module')
  71. @property
  72. def attr(self):
  73. match = self.pattern.match(self.value)
  74. return match.group('attr')
  75. @property
  76. def extras(self):
  77. match = self.pattern.match(self.value)
  78. return list(re.finditer(r'\w+', match.group('extras') or ''))
  79. @classmethod
  80. def _from_config(cls, config):
  81. return [
  82. cls(name, value, group)
  83. for group in config.sections()
  84. for name, value in config.items(group)
  85. ]
  86. @classmethod
  87. def _from_text(cls, text):
  88. config = ConfigParser(delimiters='=')
  89. # case sensitive: https://stackoverflow.com/q/1611799/812183
  90. config.optionxform = str
  91. try:
  92. config.read_string(text)
  93. except AttributeError: # pragma: nocover
  94. # Python 2 has no read_string
  95. config.readfp(io.StringIO(text))
  96. return EntryPoint._from_config(config)
  97. def __iter__(self):
  98. """
  99. Supply iter so one may construct dicts of EntryPoints easily.
  100. """
  101. return iter((self.name, self))
  102. def __reduce__(self):
  103. return (
  104. self.__class__,
  105. (self.name, self.value, self.group),
  106. )
  107. class PackagePath(pathlib.PurePosixPath):
  108. """A reference to a path in a package"""
  109. def read_text(self, encoding='utf-8'):
  110. with self.locate().open(encoding=encoding) as stream:
  111. return stream.read()
  112. def read_binary(self):
  113. with self.locate().open('rb') as stream:
  114. return stream.read()
  115. def locate(self):
  116. """Return a path-like object for this path"""
  117. return self.dist.locate_file(self)
  118. class FileHash:
  119. def __init__(self, spec):
  120. self.mode, _, self.value = spec.partition('=')
  121. def __repr__(self):
  122. return '<FileHash mode: {} value: {}>'.format(self.mode, self.value)
  123. class Distribution:
  124. """A Python distribution package."""
  125. @abc.abstractmethod
  126. def read_text(self, filename):
  127. """Attempt to load metadata file given by the name.
  128. :param filename: The name of the file in the distribution info.
  129. :return: The text if found, otherwise None.
  130. """
  131. @abc.abstractmethod
  132. def locate_file(self, path):
  133. """
  134. Given a path to a file in this distribution, return a path
  135. to it.
  136. """
  137. @classmethod
  138. def from_name(cls, name):
  139. """Return the Distribution for the given package name.
  140. :param name: The name of the distribution package to search for.
  141. :return: The Distribution instance (or subclass thereof) for the named
  142. package, if found.
  143. :raises PackageNotFoundError: When the named package's distribution
  144. metadata cannot be found.
  145. """
  146. for resolver in cls._discover_resolvers():
  147. dists = resolver(DistributionFinder.Context(name=name))
  148. dist = next(iter(dists), None)
  149. if dist is not None:
  150. return dist
  151. else:
  152. raise PackageNotFoundError(name)
  153. @classmethod
  154. def discover(cls, **kwargs):
  155. """Return an iterable of Distribution objects for all packages.
  156. Pass a ``context`` or pass keyword arguments for constructing
  157. a context.
  158. :context: A ``DistributionFinder.Context`` object.
  159. :return: Iterable of Distribution objects for all packages.
  160. """
  161. context = kwargs.pop('context', None)
  162. if context and kwargs:
  163. raise ValueError("cannot accept context and kwargs")
  164. context = context or DistributionFinder.Context(**kwargs)
  165. return itertools.chain.from_iterable(
  166. resolver(context)
  167. for resolver in cls._discover_resolvers()
  168. )
  169. @staticmethod
  170. def at(path):
  171. """Return a Distribution for the indicated metadata path
  172. :param path: a string or path-like object
  173. :return: a concrete Distribution instance for the path
  174. """
  175. return PathDistribution(pathlib.Path(path))
  176. @staticmethod
  177. def _discover_resolvers():
  178. """Search the meta_path for resolvers."""
  179. declared = (
  180. getattr(finder, 'find_distributions', None)
  181. for finder in sys.meta_path
  182. )
  183. return filter(None, declared)
  184. @classmethod
  185. def _local(cls, root='.'):
  186. from pep517 import build, meta
  187. system = build.compat_system(root)
  188. builder = functools.partial(
  189. meta.build,
  190. source_dir=root,
  191. system=system,
  192. )
  193. return PathDistribution(zipfile.Path(meta.build_as_zip(builder)))
  194. @property
  195. def metadata(self):
  196. """Return the parsed metadata for this Distribution.
  197. The returned object will have keys that name the various bits of
  198. metadata. See PEP 566 for details.
  199. """
  200. text = (
  201. self.read_text('METADATA')
  202. or self.read_text('PKG-INFO')
  203. # This last clause is here to support old egg-info files. Its
  204. # effect is to just end up using the PathDistribution's self._path
  205. # (which points to the egg-info file) attribute unchanged.
  206. or self.read_text('')
  207. )
  208. return email.message_from_string(text)
  209. @property
  210. def version(self):
  211. """Return the 'Version' metadata for the distribution package."""
  212. return self.metadata['Version']
  213. @property
  214. def entry_points(self):
  215. return EntryPoint._from_text(self.read_text('entry_points.txt'))
  216. @property
  217. def files(self):
  218. """Files in this distribution.
  219. :return: List of PackagePath for this distribution or None
  220. Result is `None` if the metadata file that enumerates files
  221. (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is
  222. missing.
  223. Result may be empty if the metadata exists but is empty.
  224. """
  225. file_lines = self._read_files_distinfo() or self._read_files_egginfo()
  226. def make_file(name, hash=None, size_str=None):
  227. result = PackagePath(name)
  228. result.hash = FileHash(hash) if hash else None
  229. result.size = int(size_str) if size_str else None
  230. result.dist = self
  231. return result
  232. return file_lines and list(starmap(make_file, csv.reader(file_lines)))
  233. def _read_files_distinfo(self):
  234. """
  235. Read the lines of RECORD
  236. """
  237. text = self.read_text('RECORD')
  238. return text and text.splitlines()
  239. def _read_files_egginfo(self):
  240. """
  241. SOURCES.txt might contain literal commas, so wrap each line
  242. in quotes.
  243. """
  244. text = self.read_text('SOURCES.txt')
  245. return text and map('"{}"'.format, text.splitlines())
  246. @property
  247. def requires(self):
  248. """Generated requirements specified for this Distribution"""
  249. reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
  250. return reqs and list(reqs)
  251. def _read_dist_info_reqs(self):
  252. return self.metadata.get_all('Requires-Dist')
  253. def _read_egg_info_reqs(self):
  254. source = self.read_text('requires.txt')
  255. return source and self._deps_from_requires_text(source)
  256. @classmethod
  257. def _deps_from_requires_text(cls, source):
  258. section_pairs = cls._read_sections(source.splitlines())
  259. sections = {
  260. section: list(map(operator.itemgetter('line'), results))
  261. for section, results in
  262. itertools.groupby(section_pairs, operator.itemgetter('section'))
  263. }
  264. return cls._convert_egg_info_reqs_to_simple_reqs(sections)
  265. @staticmethod
  266. def _read_sections(lines):
  267. section = None
  268. for line in filter(None, lines):
  269. section_match = re.match(r'\[(.*)\]$', line)
  270. if section_match:
  271. section = section_match.group(1)
  272. continue
  273. yield locals()
  274. @staticmethod
  275. def _convert_egg_info_reqs_to_simple_reqs(sections):
  276. """
  277. Historically, setuptools would solicit and store 'extra'
  278. requirements, including those with environment markers,
  279. in separate sections. More modern tools expect each
  280. dependency to be defined separately, with any relevant
  281. extras and environment markers attached directly to that
  282. requirement. This method converts the former to the
  283. latter. See _test_deps_from_requires_text for an example.
  284. """
  285. def make_condition(name):
  286. return name and 'extra == "{name}"'.format(name=name)
  287. def parse_condition(section):
  288. section = section or ''
  289. extra, sep, markers = section.partition(':')
  290. if extra and markers:
  291. markers = '({markers})'.format(markers=markers)
  292. conditions = list(filter(None, [markers, make_condition(extra)]))
  293. return '; ' + ' and '.join(conditions) if conditions else ''
  294. for section, deps in sections.items():
  295. for dep in deps:
  296. yield dep + parse_condition(section)
  297. class DistributionFinder(MetaPathFinder):
  298. """
  299. A MetaPathFinder capable of discovering installed distributions.
  300. """
  301. class Context:
  302. """
  303. Keyword arguments presented by the caller to
  304. ``distributions()`` or ``Distribution.discover()``
  305. to narrow the scope of a search for distributions
  306. in all DistributionFinders.
  307. Each DistributionFinder may expect any parameters
  308. and should attempt to honor the canonical
  309. parameters defined below when appropriate.
  310. """
  311. name = None
  312. """
  313. Specific name for which a distribution finder should match.
  314. A name of ``None`` matches all distributions.
  315. """
  316. def __init__(self, **kwargs):
  317. vars(self).update(kwargs)
  318. @property
  319. def path(self):
  320. """
  321. The path that a distribution finder should search.
  322. Typically refers to Python package paths and defaults
  323. to ``sys.path``.
  324. """
  325. return vars(self).get('path', sys.path)
  326. @abc.abstractmethod
  327. def find_distributions(self, context=Context()):
  328. """
  329. Find distributions.
  330. Return an iterable of all Distribution instances capable of
  331. loading the metadata for packages matching the ``context``,
  332. a DistributionFinder.Context instance.
  333. """
  334. class FastPath:
  335. """
  336. Micro-optimized class for searching a path for
  337. children.
  338. """
  339. def __init__(self, root):
  340. self.root = root
  341. self.base = os.path.basename(self.root).lower()
  342. def joinpath(self, child):
  343. return pathlib.Path(self.root, child)
  344. def children(self):
  345. with suppress(Exception):
  346. return os.listdir(self.root or '')
  347. with suppress(Exception):
  348. return self.zip_children()
  349. return []
  350. def zip_children(self):
  351. zip_path = zipfile.Path(self.root)
  352. names = zip_path.root.namelist()
  353. self.joinpath = zip_path.joinpath
  354. return dict.fromkeys(
  355. child.split(posixpath.sep, 1)[0]
  356. for child in names
  357. )
  358. def is_egg(self, search):
  359. base = self.base
  360. return (
  361. base == search.versionless_egg_name
  362. or base.startswith(search.prefix)
  363. and base.endswith('.egg'))
  364. def search(self, name):
  365. for child in self.children():
  366. n_low = child.lower()
  367. if (n_low in name.exact_matches
  368. or n_low.startswith(name.prefix)
  369. and n_low.endswith(name.suffixes)
  370. # legacy case:
  371. or self.is_egg(name) and n_low == 'egg-info'):
  372. yield self.joinpath(child)
  373. class Prepared:
  374. """
  375. A prepared search for metadata on a possibly-named package.
  376. """
  377. normalized = ''
  378. prefix = ''
  379. suffixes = '.dist-info', '.egg-info'
  380. exact_matches = [''][:0]
  381. versionless_egg_name = ''
  382. def __init__(self, name):
  383. self.name = name
  384. if name is None:
  385. return
  386. self.normalized = name.lower().replace('-', '_')
  387. self.prefix = self.normalized + '-'
  388. self.exact_matches = [
  389. self.normalized + suffix for suffix in self.suffixes]
  390. self.versionless_egg_name = self.normalized + '.egg'
  391. class MetadataPathFinder(DistributionFinder):
  392. @classmethod
  393. def find_distributions(cls, context=DistributionFinder.Context()):
  394. """
  395. Find distributions.
  396. Return an iterable of all Distribution instances capable of
  397. loading the metadata for packages matching ``context.name``
  398. (or all names if ``None`` indicated) along the paths in the list
  399. of directories ``context.path``.
  400. """
  401. found = cls._search_paths(context.name, context.path)
  402. return map(PathDistribution, found)
  403. @classmethod
  404. def _search_paths(cls, name, paths):
  405. """Find metadata directories in paths heuristically."""
  406. return itertools.chain.from_iterable(
  407. path.search(Prepared(name))
  408. for path in map(FastPath, paths)
  409. )
  410. class PathDistribution(Distribution):
  411. def __init__(self, path):
  412. """Construct a distribution from a path to the metadata directory.
  413. :param path: A pathlib.Path or similar object supporting
  414. .joinpath(), __div__, .parent, and .read_text().
  415. """
  416. self._path = path
  417. def read_text(self, filename):
  418. with suppress(FileNotFoundError, IsADirectoryError, KeyError,
  419. NotADirectoryError, PermissionError):
  420. return self._path.joinpath(filename).read_text(encoding='utf-8')
  421. read_text.__doc__ = Distribution.read_text.__doc__
  422. def locate_file(self, path):
  423. return self._path.parent / path
  424. def distribution(distribution_name):
  425. """Get the ``Distribution`` instance for the named package.
  426. :param distribution_name: The name of the distribution package as a string.
  427. :return: A ``Distribution`` instance (or subclass thereof).
  428. """
  429. return Distribution.from_name(distribution_name)
  430. def distributions(**kwargs):
  431. """Get all ``Distribution`` instances in the current environment.
  432. :return: An iterable of ``Distribution`` instances.
  433. """
  434. return Distribution.discover(**kwargs)
  435. def metadata(distribution_name):
  436. """Get the metadata for the named package.
  437. :param distribution_name: The name of the distribution package to query.
  438. :return: An email.Message containing the parsed metadata.
  439. """
  440. return Distribution.from_name(distribution_name).metadata
  441. def version(distribution_name):
  442. """Get the version string for the named package.
  443. :param distribution_name: The name of the distribution package to query.
  444. :return: The version string for the package as defined in the package's
  445. "Version" metadata key.
  446. """
  447. return distribution(distribution_name).version
  448. def entry_points():
  449. """Return EntryPoint objects for all installed packages.
  450. :return: EntryPoint objects for all installed packages.
  451. """
  452. eps = itertools.chain.from_iterable(
  453. dist.entry_points for dist in distributions())
  454. by_group = operator.attrgetter('group')
  455. ordered = sorted(eps, key=by_group)
  456. grouped = itertools.groupby(ordered, by_group)
  457. return {
  458. group: tuple(eps)
  459. for group, eps in grouped
  460. }
  461. def files(distribution_name):
  462. """Return a list of files for the named package.
  463. :param distribution_name: The name of the distribution package to query.
  464. :return: List of files composing the distribution.
  465. """
  466. return distribution(distribution_name).files
  467. def requires(distribution_name):
  468. """
  469. Return a list of requirements for the named package.
  470. :return: An iterator of requirements, suitable for
  471. packaging.requirement.Requirement.
  472. """
  473. return distribution(distribution_name).requires