pkg_resources.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import email.message
  2. import email.parser
  3. import logging
  4. import os
  5. import zipfile
  6. from typing import Collection, Iterable, Iterator, List, Mapping, NamedTuple, Optional
  7. from pip._vendor import pkg_resources
  8. from pip._vendor.packaging.requirements import Requirement
  9. from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
  10. from pip._vendor.packaging.version import parse as parse_version
  11. from pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel
  12. from pip._internal.utils.egg_link import egg_link_path_from_location
  13. from pip._internal.utils.misc import display_path, normalize_path
  14. from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file
  15. from .base import (
  16. BaseDistribution,
  17. BaseEntryPoint,
  18. BaseEnvironment,
  19. DistributionVersion,
  20. InfoPath,
  21. Wheel,
  22. )
  23. logger = logging.getLogger(__name__)
  24. class EntryPoint(NamedTuple):
  25. name: str
  26. value: str
  27. group: str
  28. class InMemoryMetadata:
  29. """IMetadataProvider that reads metadata files from a dictionary.
  30. This also maps metadata decoding exceptions to our internal exception type.
  31. """
  32. def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:
  33. self._metadata = metadata
  34. self._wheel_name = wheel_name
  35. def has_metadata(self, name: str) -> bool:
  36. return name in self._metadata
  37. def get_metadata(self, name: str) -> str:
  38. try:
  39. return self._metadata[name].decode()
  40. except UnicodeDecodeError as e:
  41. # Augment the default error with the origin of the file.
  42. raise UnsupportedWheel(
  43. f"Error decoding metadata for {self._wheel_name}: {e} in {name} file"
  44. )
  45. def get_metadata_lines(self, name: str) -> Iterable[str]:
  46. return pkg_resources.yield_lines(self.get_metadata(name))
  47. def metadata_isdir(self, name: str) -> bool:
  48. return False
  49. def metadata_listdir(self, name: str) -> List[str]:
  50. return []
  51. def run_script(self, script_name: str, namespace: str) -> None:
  52. pass
  53. class Distribution(BaseDistribution):
  54. def __init__(self, dist: pkg_resources.Distribution) -> None:
  55. self._dist = dist
  56. @classmethod
  57. def from_directory(cls, directory: str) -> BaseDistribution:
  58. dist_dir = directory.rstrip(os.sep)
  59. # Build a PathMetadata object, from path to metadata. :wink:
  60. base_dir, dist_dir_name = os.path.split(dist_dir)
  61. metadata = pkg_resources.PathMetadata(base_dir, dist_dir)
  62. # Determine the correct Distribution object type.
  63. if dist_dir.endswith(".egg-info"):
  64. dist_cls = pkg_resources.Distribution
  65. dist_name = os.path.splitext(dist_dir_name)[0]
  66. else:
  67. assert dist_dir.endswith(".dist-info")
  68. dist_cls = pkg_resources.DistInfoDistribution
  69. dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0]
  70. dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata)
  71. return cls(dist)
  72. @classmethod
  73. def from_metadata_file_contents(
  74. cls,
  75. metadata_contents: bytes,
  76. filename: str,
  77. project_name: str,
  78. ) -> BaseDistribution:
  79. metadata_dict = {
  80. "METADATA": metadata_contents,
  81. }
  82. dist = pkg_resources.DistInfoDistribution(
  83. location=filename,
  84. metadata=InMemoryMetadata(metadata_dict, filename),
  85. project_name=project_name,
  86. )
  87. return cls(dist)
  88. @classmethod
  89. def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:
  90. try:
  91. with wheel.as_zipfile() as zf:
  92. info_dir, _ = parse_wheel(zf, name)
  93. metadata_dict = {
  94. path.split("/", 1)[-1]: read_wheel_metadata_file(zf, path)
  95. for path in zf.namelist()
  96. if path.startswith(f"{info_dir}/")
  97. }
  98. except zipfile.BadZipFile as e:
  99. raise InvalidWheel(wheel.location, name) from e
  100. except UnsupportedWheel as e:
  101. raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
  102. dist = pkg_resources.DistInfoDistribution(
  103. location=wheel.location,
  104. metadata=InMemoryMetadata(metadata_dict, wheel.location),
  105. project_name=name,
  106. )
  107. return cls(dist)
  108. @property
  109. def location(self) -> Optional[str]:
  110. return self._dist.location
  111. @property
  112. def installed_location(self) -> Optional[str]:
  113. egg_link = egg_link_path_from_location(self.raw_name)
  114. if egg_link:
  115. location = egg_link
  116. elif self.location:
  117. location = self.location
  118. else:
  119. return None
  120. return normalize_path(location)
  121. @property
  122. def info_location(self) -> Optional[str]:
  123. return self._dist.egg_info
  124. @property
  125. def installed_by_distutils(self) -> bool:
  126. # A distutils-installed distribution is provided by FileMetadata. This
  127. # provider has a "path" attribute not present anywhere else. Not the
  128. # best introspection logic, but pip has been doing this for a long time.
  129. try:
  130. return bool(self._dist._provider.path)
  131. except AttributeError:
  132. return False
  133. @property
  134. def canonical_name(self) -> NormalizedName:
  135. return canonicalize_name(self._dist.project_name)
  136. @property
  137. def version(self) -> DistributionVersion:
  138. return parse_version(self._dist.version)
  139. def is_file(self, path: InfoPath) -> bool:
  140. return self._dist.has_metadata(str(path))
  141. def iter_distutils_script_names(self) -> Iterator[str]:
  142. yield from self._dist.metadata_listdir("scripts")
  143. def read_text(self, path: InfoPath) -> str:
  144. name = str(path)
  145. if not self._dist.has_metadata(name):
  146. raise FileNotFoundError(name)
  147. content = self._dist.get_metadata(name)
  148. if content is None:
  149. raise NoneMetadataError(self, name)
  150. return content
  151. def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
  152. for group, entries in self._dist.get_entry_map().items():
  153. for name, entry_point in entries.items():
  154. name, _, value = str(entry_point).partition("=")
  155. yield EntryPoint(name=name.strip(), value=value.strip(), group=group)
  156. def _metadata_impl(self) -> email.message.Message:
  157. """
  158. :raises NoneMetadataError: if the distribution reports `has_metadata()`
  159. True but `get_metadata()` returns None.
  160. """
  161. if isinstance(self._dist, pkg_resources.DistInfoDistribution):
  162. metadata_name = "METADATA"
  163. else:
  164. metadata_name = "PKG-INFO"
  165. try:
  166. metadata = self.read_text(metadata_name)
  167. except FileNotFoundError:
  168. if self.location:
  169. displaying_path = display_path(self.location)
  170. else:
  171. displaying_path = repr(self.location)
  172. logger.warning("No metadata found in %s", displaying_path)
  173. metadata = ""
  174. feed_parser = email.parser.FeedParser()
  175. feed_parser.feed(metadata)
  176. return feed_parser.close()
  177. def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
  178. if extras: # pkg_resources raises on invalid extras, so we sanitize.
  179. extras = frozenset(extras).intersection(self._dist.extras)
  180. return self._dist.requires(extras)
  181. def iter_provided_extras(self) -> Iterable[str]:
  182. return self._dist.extras
  183. class Environment(BaseEnvironment):
  184. def __init__(self, ws: pkg_resources.WorkingSet) -> None:
  185. self._ws = ws
  186. @classmethod
  187. def default(cls) -> BaseEnvironment:
  188. return cls(pkg_resources.working_set)
  189. @classmethod
  190. def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:
  191. return cls(pkg_resources.WorkingSet(paths))
  192. def _iter_distributions(self) -> Iterator[BaseDistribution]:
  193. for dist in self._ws:
  194. yield Distribution(dist)
  195. def _search_distribution(self, name: str) -> Optional[BaseDistribution]:
  196. """Find a distribution matching the ``name`` in the environment.
  197. This searches from *all* distributions available in the environment, to
  198. match the behavior of ``pkg_resources.get_distribution()``.
  199. """
  200. canonical_name = canonicalize_name(name)
  201. for dist in self.iter_all_distributions():
  202. if dist.canonical_name == canonical_name:
  203. return dist
  204. return None
  205. def get_distribution(self, name: str) -> Optional[BaseDistribution]:
  206. # Search the distribution by looking through the working set.
  207. dist = self._search_distribution(name)
  208. if dist:
  209. return dist
  210. # If distribution could not be found, call working_set.require to
  211. # update the working set, and try to find the distribution again.
  212. # This might happen for e.g. when you install a package twice, once
  213. # using setup.py develop and again using setup.py install. Now when
  214. # running pip uninstall twice, the package gets removed from the
  215. # working set in the first uninstall, so we have to populate the
  216. # working set again so that pip knows about it and the packages gets
  217. # picked up and is successfully uninstalled the second time too.
  218. try:
  219. # We didn't pass in any version specifiers, so this can never
  220. # raise pkg_resources.VersionConflict.
  221. self._ws.require(name)
  222. except pkg_resources.DistributionNotFound:
  223. return None
  224. return self._search_distribution(name)