metadata.py 16 KB

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