api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import io
  2. import re
  3. import abc
  4. import csv
  5. import sys
  6. import email
  7. import operator
  8. import functools
  9. import itertools
  10. import collections
  11. from importlib import import_module
  12. from itertools import starmap
  13. if sys.version_info > (3,): # pragma: nocover
  14. import pathlib
  15. from configparser import ConfigParser
  16. else: # pragma: nocover
  17. import pathlib2 as pathlib
  18. from backports.configparser import ConfigParser
  19. from itertools import imap as map # type: ignore
  20. try:
  21. BaseClass = ModuleNotFoundError
  22. except NameError: # pragma: nocover
  23. BaseClass = ImportError # type: ignore
  24. __metaclass__ = type
  25. class PackageNotFoundError(BaseClass):
  26. """The package was not found."""
  27. class EntryPoint(collections.namedtuple('EntryPointBase', 'name value group')):
  28. """An entry point as defined by Python packaging conventions."""
  29. pattern = re.compile(
  30. r'(?P<module>[\w.]+)\s*'
  31. r'(:\s*(?P<attr>[\w.]+))?\s*'
  32. r'(?P<extras>\[.*\])?\s*$'
  33. )
  34. """
  35. A regular expression describing the syntax for an entry point,
  36. which might look like:
  37. - module
  38. - package.module
  39. - package.module:attribute
  40. - package.module:object.attribute
  41. - package.module:attr [extra1, extra2]
  42. Other combinations are possible as well.
  43. The expression is lenient about whitespace around the ':',
  44. following the attr, and following any extras.
  45. """
  46. def load(self):
  47. """Load the entry point from its definition. If only a module
  48. is indicated by the value, return that module. Otherwise,
  49. return the named object.
  50. """
  51. match = self.pattern.match(self.value)
  52. module = import_module(match.group('module'))
  53. attrs = filter(None, match.group('attr').split('.'))
  54. return functools.reduce(getattr, attrs, module)
  55. @property
  56. def extras(self):
  57. match = self.pattern.match(self.value)
  58. return list(re.finditer(r'\w+', match.group('extras') or ''))
  59. @classmethod
  60. def _from_config(cls, config):
  61. return [
  62. cls(name, value, group)
  63. for group in config.sections()
  64. for name, value in config.items(group)
  65. ]
  66. @classmethod
  67. def _from_text(cls, text):
  68. config = ConfigParser()
  69. try:
  70. config.read_string(text)
  71. except AttributeError: # pragma: nocover
  72. # Python 2 has no read_string
  73. config.readfp(io.StringIO(text))
  74. return EntryPoint._from_config(config)
  75. def __iter__(self):
  76. """
  77. Supply iter so one may construct dicts of EntryPoints easily.
  78. """
  79. return iter((self.name, self))
  80. class PackagePath(pathlib.PosixPath):
  81. """A reference to a path in a package"""
  82. def read_text(self, encoding='utf-8'):
  83. with self.locate().open(encoding=encoding) as stream:
  84. return stream.read()
  85. def read_binary(self):
  86. with self.locate().open('rb') as stream:
  87. return stream.read()
  88. def locate(self):
  89. """Return a path-like object for this path"""
  90. return self.dist.locate_file(self)
  91. class FileHash:
  92. def __init__(self, spec):
  93. self.mode, _, self.value = spec.partition('=')
  94. def __repr__(self):
  95. return '<FileHash mode: {} value: {}>'.format(self.mode, self.value)
  96. class Distribution:
  97. """A Python distribution package."""
  98. @abc.abstractmethod
  99. def read_text(self, filename):
  100. """Attempt to load metadata file given by the name.
  101. :param filename: The name of the file in the distribution info.
  102. :return: The text if found, otherwise None.
  103. """
  104. @abc.abstractmethod
  105. def locate_file(self, path):
  106. """
  107. Given a path to a file in this distribution, return a path
  108. to it.
  109. """
  110. @classmethod
  111. def from_name(cls, name):
  112. """Return the Distribution for the given package name.
  113. :param name: The name of the distribution package to search for.
  114. :return: The Distribution instance (or subclass thereof) for the named
  115. package, if found.
  116. :raises PackageNotFoundError: When the named package's distribution
  117. metadata cannot be found.
  118. """
  119. for resolver in cls._discover_resolvers():
  120. dists = resolver(name)
  121. dist = next(dists, None)
  122. if dist is not None:
  123. return dist
  124. else:
  125. raise PackageNotFoundError(name)
  126. @classmethod
  127. def discover(cls):
  128. """Return an iterable of Distribution objects for all packages.
  129. :return: Iterable of Distribution objects for all packages.
  130. """
  131. return itertools.chain.from_iterable(
  132. resolver()
  133. for resolver in cls._discover_resolvers()
  134. )
  135. @staticmethod
  136. def _discover_resolvers():
  137. """Search the meta_path for resolvers."""
  138. declared = (
  139. getattr(finder, 'find_distributions', None)
  140. for finder in sys.meta_path
  141. )
  142. return filter(None, declared)
  143. @classmethod
  144. def find_local(cls):
  145. dists = itertools.chain.from_iterable(
  146. resolver(path=['.'])
  147. for resolver in cls._discover_resolvers()
  148. )
  149. dist, = dists
  150. return dist
  151. @property
  152. def metadata(self):
  153. """Return the parsed metadata for this Distribution.
  154. The returned object will have keys that name the various bits of
  155. metadata. See PEP 566 for details.
  156. """
  157. text = self.read_text('METADATA') or self.read_text('PKG-INFO')
  158. return _email_message_from_string(text)
  159. @property
  160. def version(self):
  161. """Return the 'Version' metadata for the distribution package."""
  162. return self.metadata['Version']
  163. @property
  164. def entry_points(self):
  165. return EntryPoint._from_text(self.read_text('entry_points.txt'))
  166. @property
  167. def files(self):
  168. file_lines = self._read_files_distinfo() or self._read_files_egginfo()
  169. def make_file(name, hash=None, size_str=None):
  170. result = PackagePath(name)
  171. result.hash = FileHash(hash) if hash else None
  172. result.size = int(size_str) if size_str else None
  173. result.dist = self
  174. return result
  175. return file_lines and starmap(make_file, csv.reader(file_lines))
  176. def _read_files_distinfo(self):
  177. """
  178. Read the lines of RECORD
  179. """
  180. text = self.read_text('RECORD')
  181. return text and text.splitlines()
  182. def _read_files_egginfo(self):
  183. """
  184. SOURCES.txt might contain literal commas, so wrap each line
  185. in quotes.
  186. """
  187. text = self.read_text('SOURCES.txt')
  188. return text and map('"{}"'.format, text.splitlines())
  189. @property
  190. def requires(self):
  191. return self._read_dist_info_reqs() or self._read_egg_info_reqs()
  192. def _read_dist_info_reqs(self):
  193. spec = self.metadata['Requires-Dist']
  194. return spec and filter(None, spec.splitlines())
  195. def _read_egg_info_reqs(self):
  196. source = self.read_text('requires.txt')
  197. return self._deps_from_requires_text(source)
  198. @classmethod
  199. def _deps_from_requires_text(cls, source):
  200. section_pairs = cls._read_sections(source.splitlines())
  201. sections = {
  202. section: list(map(operator.itemgetter('line'), results))
  203. for section, results in
  204. itertools.groupby(section_pairs, operator.itemgetter('section'))
  205. }
  206. return cls._convert_egg_info_reqs_to_simple_reqs(sections)
  207. @staticmethod
  208. def _read_sections(lines):
  209. section = None
  210. for line in filter(None, lines):
  211. section_match = re.match(r'\[(.*)\]$', line)
  212. if section_match:
  213. section = section_match.group(1)
  214. continue
  215. yield locals()
  216. @staticmethod
  217. def _convert_egg_info_reqs_to_simple_reqs(sections):
  218. """
  219. Historically, setuptools would solicit and store 'extra'
  220. requirements, including those with environment markers,
  221. in separate sections. More modern tools expect each
  222. dependency to be defined separately, with any relevant
  223. extras and environment markers attached directly to that
  224. requirement. This method converts the former to the
  225. latter. See _test_deps_from_requires_text for an example.
  226. """
  227. def make_condition(name):
  228. return name and 'extra == "{name}"'.format(name=name)
  229. def parse_condition(section):
  230. section = section or ''
  231. extra, sep, markers = section.partition(':')
  232. if extra and markers:
  233. markers = '({markers})'.format(markers=markers)
  234. conditions = list(filter(None, [markers, make_condition(extra)]))
  235. return '; ' + ' and '.join(conditions) if conditions else ''
  236. for section, deps in sections.items():
  237. for dep in deps:
  238. yield dep + parse_condition(section)
  239. def _email_message_from_string(text):
  240. # Work around https://bugs.python.org/issue25545 where
  241. # email.message_from_string cannot handle Unicode on Python 2.
  242. if sys.version_info < (3,): # nocoverpy3
  243. io_buffer = io.StringIO(text)
  244. return email.message_from_file(io_buffer)
  245. return email.message_from_string(text) # nocoverpy2
  246. def distribution(package):
  247. """Get the ``Distribution`` instance for the given package.
  248. :param package: The name of the package as a string.
  249. :return: A ``Distribution`` instance (or subclass thereof).
  250. """
  251. return Distribution.from_name(package)
  252. def distributions():
  253. """Get all ``Distribution`` instances in the current environment.
  254. :return: An iterable of ``Distribution`` instances.
  255. """
  256. return Distribution.discover()
  257. def local_distribution():
  258. """Get the ``Distribution`` instance for the package in CWD.
  259. :return: A ``Distribution`` instance (or subclass thereof).
  260. """
  261. return Distribution.find_local()
  262. def metadata(package):
  263. """Get the metadata for the package.
  264. :param package: The name of the distribution package to query.
  265. :return: An email.Message containing the parsed metadata.
  266. """
  267. return Distribution.from_name(package).metadata
  268. def version(package):
  269. """Get the version string for the named package.
  270. :param package: The name of the distribution package to query.
  271. :return: The version string for the package as defined in the package's
  272. "Version" metadata key.
  273. """
  274. return distribution(package).version
  275. def entry_points(name=None):
  276. """Return EntryPoint objects for all installed packages.
  277. :return: EntryPoint objects for all installed packages.
  278. """
  279. eps = itertools.chain.from_iterable(
  280. dist.entry_points for dist in distributions())
  281. by_group = operator.attrgetter('group')
  282. ordered = sorted(eps, key=by_group)
  283. grouped = itertools.groupby(ordered, by_group)
  284. return {
  285. group: tuple(eps)
  286. for group, eps in grouped
  287. }
  288. def files(package):
  289. return distribution(package).files
  290. def requires(package):
  291. """
  292. Return a list of requirements for the indicated distribution.
  293. :return: An iterator of requirements, suitable for
  294. packaging.requirement.Requirement.
  295. """
  296. return distribution(package).requires