m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

702 lines
25 KiB

6 months ago
  1. import csv
  2. import email.message
  3. import functools
  4. import json
  5. import logging
  6. import pathlib
  7. import re
  8. import zipfile
  9. from typing import (
  10. IO,
  11. TYPE_CHECKING,
  12. Any,
  13. Collection,
  14. Container,
  15. Dict,
  16. Iterable,
  17. Iterator,
  18. List,
  19. NamedTuple,
  20. Optional,
  21. Tuple,
  22. Union,
  23. )
  24. from pip._vendor.packaging.requirements import Requirement
  25. from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
  26. from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
  27. from pip._vendor.packaging.version import LegacyVersion, Version
  28. from pip._internal.exceptions import NoneMetadataError
  29. from pip._internal.locations import site_packages, user_site
  30. from pip._internal.models.direct_url import (
  31. DIRECT_URL_METADATA_NAME,
  32. DirectUrl,
  33. DirectUrlValidationError,
  34. )
  35. from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.
  36. from pip._internal.utils.egg_link import egg_link_path_from_sys_path
  37. from pip._internal.utils.misc import is_local, normalize_path
  38. from pip._internal.utils.urls import url_to_path
  39. from ._json import msg_to_json
  40. if TYPE_CHECKING:
  41. from typing import Protocol
  42. else:
  43. Protocol = object
  44. DistributionVersion = Union[LegacyVersion, Version]
  45. InfoPath = Union[str, pathlib.PurePath]
  46. logger = logging.getLogger(__name__)
  47. class BaseEntryPoint(Protocol):
  48. @property
  49. def name(self) -> str:
  50. raise NotImplementedError()
  51. @property
  52. def value(self) -> str:
  53. raise NotImplementedError()
  54. @property
  55. def group(self) -> str:
  56. raise NotImplementedError()
  57. def _convert_installed_files_path(
  58. entry: Tuple[str, ...],
  59. info: Tuple[str, ...],
  60. ) -> str:
  61. """Convert a legacy installed-files.txt path into modern RECORD path.
  62. The legacy format stores paths relative to the info directory, while the
  63. modern format stores paths relative to the package root, e.g. the
  64. site-packages directory.
  65. :param entry: Path parts of the installed-files.txt entry.
  66. :param info: Path parts of the egg-info directory relative to package root.
  67. :returns: The converted entry.
  68. For best compatibility with symlinks, this does not use ``abspath()`` or
  69. ``Path.resolve()``, but tries to work with path parts:
  70. 1. While ``entry`` starts with ``..``, remove the equal amounts of parts
  71. from ``info``; if ``info`` is empty, start appending ``..`` instead.
  72. 2. Join the two directly.
  73. """
  74. while entry and entry[0] == "..":
  75. if not info or info[-1] == "..":
  76. info += ("..",)
  77. else:
  78. info = info[:-1]
  79. entry = entry[1:]
  80. return str(pathlib.Path(*info, *entry))
  81. class RequiresEntry(NamedTuple):
  82. requirement: str
  83. extra: str
  84. marker: str
  85. class BaseDistribution(Protocol):
  86. @classmethod
  87. def from_directory(cls, directory: str) -> "BaseDistribution":
  88. """Load the distribution from a metadata directory.
  89. :param directory: Path to a metadata directory, e.g. ``.dist-info``.
  90. """
  91. raise NotImplementedError()
  92. @classmethod
  93. def from_metadata_file_contents(
  94. cls,
  95. metadata_contents: bytes,
  96. filename: str,
  97. project_name: str,
  98. ) -> "BaseDistribution":
  99. """Load the distribution from the contents of a METADATA file.
  100. This is used to implement PEP 658 by generating a "shallow" dist object that can
  101. be used for resolution without downloading or building the actual dist yet.
  102. :param metadata_contents: The contents of a METADATA file.
  103. :param filename: File name for the dist with this metadata.
  104. :param project_name: Name of the project this dist represents.
  105. """
  106. raise NotImplementedError()
  107. @classmethod
  108. def from_wheel(cls, wheel: "Wheel", name: str) -> "BaseDistribution":
  109. """Load the distribution from a given wheel.
  110. :param wheel: A concrete wheel definition.
  111. :param name: File name of the wheel.
  112. :raises InvalidWheel: Whenever loading of the wheel causes a
  113. :py:exc:`zipfile.BadZipFile` exception to be thrown.
  114. :raises UnsupportedWheel: If the wheel is a valid zip, but malformed
  115. internally.
  116. """
  117. raise NotImplementedError()
  118. def __repr__(self) -> str:
  119. return f"{self.raw_name} {self.version} ({self.location})"
  120. def __str__(self) -> str:
  121. return f"{self.raw_name} {self.version}"
  122. @property
  123. def location(self) -> Optional[str]:
  124. """Where the distribution is loaded from.
  125. A string value is not necessarily a filesystem path, since distributions
  126. can be loaded from other sources, e.g. arbitrary zip archives. ``None``
  127. means the distribution is created in-memory.
  128. Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
  129. this is a symbolic link, we want to preserve the relative path between
  130. it and files in the distribution.
  131. """
  132. raise NotImplementedError()
  133. @property
  134. def editable_project_location(self) -> Optional[str]:
  135. """The project location for editable distributions.
  136. This is the directory where pyproject.toml or setup.py is located.
  137. None if the distribution is not installed in editable mode.
  138. """
  139. # TODO: this property is relatively costly to compute, memoize it ?
  140. direct_url = self.direct_url
  141. if direct_url:
  142. if direct_url.is_local_editable():
  143. return url_to_path(direct_url.url)
  144. else:
  145. # Search for an .egg-link file by walking sys.path, as it was
  146. # done before by dist_is_editable().
  147. egg_link_path = egg_link_path_from_sys_path(self.raw_name)
  148. if egg_link_path:
  149. # TODO: get project location from second line of egg_link file
  150. # (https://github.com/pypa/pip/issues/10243)
  151. return self.location
  152. return None
  153. @property
  154. def installed_location(self) -> Optional[str]:
  155. """The distribution's "installed" location.
  156. This should generally be a ``site-packages`` directory. This is
  157. usually ``dist.location``, except for legacy develop-installed packages,
  158. where ``dist.location`` is the source code location, and this is where
  159. the ``.egg-link`` file is.
  160. The returned location is normalized (in particular, with symlinks removed).
  161. """
  162. raise NotImplementedError()
  163. @property
  164. def info_location(self) -> Optional[str]:
  165. """Location of the .[egg|dist]-info directory or file.
  166. Similarly to ``location``, a string value is not necessarily a
  167. filesystem path. ``None`` means the distribution is created in-memory.
  168. For a modern .dist-info installation on disk, this should be something
  169. like ``{location}/{raw_name}-{version}.dist-info``.
  170. Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
  171. this is a symbolic link, we want to preserve the relative path between
  172. it and other files in the distribution.
  173. """
  174. raise NotImplementedError()
  175. @property
  176. def installed_by_distutils(self) -> bool:
  177. """Whether this distribution is installed with legacy distutils format.
  178. A distribution installed with "raw" distutils not patched by setuptools
  179. uses one single file at ``info_location`` to store metadata. We need to
  180. treat this specially on uninstallation.
  181. """
  182. info_location = self.info_location
  183. if not info_location:
  184. return False
  185. return pathlib.Path(info_location).is_file()
  186. @property
  187. def installed_as_egg(self) -> bool:
  188. """Whether this distribution is installed as an egg.
  189. This usually indicates the distribution was installed by (older versions
  190. of) easy_install.
  191. """
  192. location = self.location
  193. if not location:
  194. return False
  195. return location.endswith(".egg")
  196. @property
  197. def installed_with_setuptools_egg_info(self) -> bool:
  198. """Whether this distribution is installed with the ``.egg-info`` format.
  199. This usually indicates the distribution was installed with setuptools
  200. with an old pip version or with ``single-version-externally-managed``.
  201. Note that this ensure the metadata store is a directory. distutils can
  202. also installs an ``.egg-info``, but as a file, not a directory. This
  203. property is *False* for that case. Also see ``installed_by_distutils``.
  204. """
  205. info_location = self.info_location
  206. if not info_location:
  207. return False
  208. if not info_location.endswith(".egg-info"):
  209. return False
  210. return pathlib.Path(info_location).is_dir()
  211. @property
  212. def installed_with_dist_info(self) -> bool:
  213. """Whether this distribution is installed with the "modern format".
  214. This indicates a "modern" installation, e.g. storing metadata in the
  215. ``.dist-info`` directory. This applies to installations made by
  216. setuptools (but through pip, not directly), or anything using the
  217. standardized build backend interface (PEP 517).
  218. """
  219. info_location = self.info_location
  220. if not info_location:
  221. return False
  222. if not info_location.endswith(".dist-info"):
  223. return False
  224. return pathlib.Path(info_location).is_dir()
  225. @property
  226. def canonical_name(self) -> NormalizedName:
  227. raise NotImplementedError()
  228. @property
  229. def version(self) -> DistributionVersion:
  230. raise NotImplementedError()
  231. @property
  232. def setuptools_filename(self) -> str:
  233. """Convert a project name to its setuptools-compatible filename.
  234. This is a copy of ``pkg_resources.to_filename()`` for compatibility.
  235. """
  236. return self.raw_name.replace("-", "_")
  237. @property
  238. def direct_url(self) -> Optional[DirectUrl]:
  239. """Obtain a DirectUrl from this distribution.
  240. Returns None if the distribution has no `direct_url.json` metadata,
  241. or if `direct_url.json` is invalid.
  242. """
  243. try:
  244. content = self.read_text(DIRECT_URL_METADATA_NAME)
  245. except FileNotFoundError:
  246. return None
  247. try:
  248. return DirectUrl.from_json(content)
  249. except (
  250. UnicodeDecodeError,
  251. json.JSONDecodeError,
  252. DirectUrlValidationError,
  253. ) as e:
  254. logger.warning(
  255. "Error parsing %s for %s: %s",
  256. DIRECT_URL_METADATA_NAME,
  257. self.canonical_name,
  258. e,
  259. )
  260. return None
  261. @property
  262. def installer(self) -> str:
  263. try:
  264. installer_text = self.read_text("INSTALLER")
  265. except (OSError, ValueError, NoneMetadataError):
  266. return "" # Fail silently if the installer file cannot be read.
  267. for line in installer_text.splitlines():
  268. cleaned_line = line.strip()
  269. if cleaned_line:
  270. return cleaned_line
  271. return ""
  272. @property
  273. def requested(self) -> bool:
  274. return self.is_file("REQUESTED")
  275. @property
  276. def editable(self) -> bool:
  277. return bool(self.editable_project_location)
  278. @property
  279. def local(self) -> bool:
  280. """If distribution is installed in the current virtual environment.
  281. Always True if we're not in a virtualenv.
  282. """
  283. if self.installed_location is None:
  284. return False
  285. return is_local(self.installed_location)
  286. @property
  287. def in_usersite(self) -> bool:
  288. if self.installed_location is None or user_site is None:
  289. return False
  290. return self.installed_location.startswith(normalize_path(user_site))
  291. @property
  292. def in_site_packages(self) -> bool:
  293. if self.installed_location is None or site_packages is None:
  294. return False
  295. return self.installed_location.startswith(normalize_path(site_packages))
  296. def is_file(self, path: InfoPath) -> bool:
  297. """Check whether an entry in the info directory is a file."""
  298. raise NotImplementedError()
  299. def iter_distutils_script_names(self) -> Iterator[str]:
  300. """Find distutils 'scripts' entries metadata.
  301. If 'scripts' is supplied in ``setup.py``, distutils records those in the
  302. installed distribution's ``scripts`` directory, a file for each script.
  303. """
  304. raise NotImplementedError()
  305. def read_text(self, path: InfoPath) -> str:
  306. """Read a file in the info directory.
  307. :raise FileNotFoundError: If ``path`` does not exist in the directory.
  308. :raise NoneMetadataError: If ``path`` exists in the info directory, but
  309. cannot be read.
  310. """
  311. raise NotImplementedError()
  312. def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
  313. raise NotImplementedError()
  314. def _metadata_impl(self) -> email.message.Message:
  315. raise NotImplementedError()
  316. @functools.lru_cache(maxsize=1)
  317. def _metadata_cached(self) -> email.message.Message:
  318. # When we drop python 3.7 support, move this to the metadata property and use
  319. # functools.cached_property instead of lru_cache.
  320. metadata = self._metadata_impl()
  321. self._add_egg_info_requires(metadata)
  322. return metadata
  323. @property
  324. def metadata(self) -> email.message.Message:
  325. """Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
  326. This should return an empty message if the metadata file is unavailable.
  327. :raises NoneMetadataError: If the metadata file is available, but does
  328. not contain valid metadata.
  329. """
  330. return self._metadata_cached()
  331. @property
  332. def metadata_dict(self) -> Dict[str, Any]:
  333. """PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO.
  334. This should return an empty dict if the metadata file is unavailable.
  335. :raises NoneMetadataError: If the metadata file is available, but does
  336. not contain valid metadata.
  337. """
  338. return msg_to_json(self.metadata)
  339. @property
  340. def metadata_version(self) -> Optional[str]:
  341. """Value of "Metadata-Version:" in distribution metadata, if available."""
  342. return self.metadata.get("Metadata-Version")
  343. @property
  344. def raw_name(self) -> str:
  345. """Value of "Name:" in distribution metadata."""
  346. # The metadata should NEVER be missing the Name: key, but if it somehow
  347. # does, fall back to the known canonical name.
  348. return self.metadata.get("Name", self.canonical_name)
  349. @property
  350. def requires_python(self) -> SpecifierSet:
  351. """Value of "Requires-Python:" in distribution metadata.
  352. If the key does not exist or contains an invalid value, an empty
  353. SpecifierSet should be returned.
  354. """
  355. value = self.metadata.get("Requires-Python")
  356. if value is None:
  357. return SpecifierSet()
  358. try:
  359. # Convert to str to satisfy the type checker; this can be a Header object.
  360. spec = SpecifierSet(str(value))
  361. except InvalidSpecifier as e:
  362. message = "Package %r has an invalid Requires-Python: %s"
  363. logger.warning(message, self.raw_name, e)
  364. return SpecifierSet()
  365. return spec
  366. def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
  367. """Dependencies of this distribution.
  368. For modern .dist-info distributions, this is the collection of
  369. "Requires-Dist:" entries in distribution metadata.
  370. """
  371. raise NotImplementedError()
  372. def iter_provided_extras(self) -> Iterable[str]:
  373. """Extras provided by this distribution.
  374. For modern .dist-info distributions, this is the collection of
  375. "Provides-Extra:" entries in distribution metadata.
  376. The return value of this function is not particularly useful other than
  377. display purposes due to backward compatibility issues and the extra
  378. names being poorly normalized prior to PEP 685. If you want to perform
  379. logic operations on extras, use :func:`is_extra_provided` instead.
  380. """
  381. raise NotImplementedError()
  382. def is_extra_provided(self, extra: str) -> bool:
  383. """Check whether an extra is provided by this distribution.
  384. This is needed mostly for compatibility issues with pkg_resources not
  385. following the extra normalization rules defined in PEP 685.
  386. """
  387. raise NotImplementedError()
  388. def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:
  389. try:
  390. text = self.read_text("RECORD")
  391. except FileNotFoundError:
  392. return None
  393. # This extra Path-str cast normalizes entries.
  394. return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
  395. def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:
  396. try:
  397. text = self.read_text("installed-files.txt")
  398. except FileNotFoundError:
  399. return None
  400. paths = (p for p in text.splitlines(keepends=False) if p)
  401. root = self.location
  402. info = self.info_location
  403. if root is None or info is None:
  404. return paths
  405. try:
  406. info_rel = pathlib.Path(info).relative_to(root)
  407. except ValueError: # info is not relative to root.
  408. return paths
  409. if not info_rel.parts: # info *is* root.
  410. return paths
  411. return (
  412. _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
  413. for p in paths
  414. )
  415. def iter_declared_entries(self) -> Optional[Iterator[str]]:
  416. """Iterate through file entries declared in this distribution.
  417. For modern .dist-info distributions, this is the files listed in the
  418. ``RECORD`` metadata file. For legacy setuptools distributions, this
  419. comes from ``installed-files.txt``, with entries normalized to be
  420. compatible with the format used by ``RECORD``.
  421. :return: An iterator for listed entries, or None if the distribution
  422. contains neither ``RECORD`` nor ``installed-files.txt``.
  423. """
  424. return (
  425. self._iter_declared_entries_from_record()
  426. or self._iter_declared_entries_from_legacy()
  427. )
  428. def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]:
  429. """Parse a ``requires.txt`` in an egg-info directory.
  430. This is an INI-ish format where an egg-info stores dependencies. A
  431. section name describes extra other environment markers, while each entry
  432. is an arbitrary string (not a key-value pair) representing a dependency
  433. as a requirement string (no markers).
  434. There is a construct in ``importlib.metadata`` called ``Sectioned`` that
  435. does mostly the same, but the format is currently considered private.
  436. """
  437. try:
  438. content = self.read_text("requires.txt")
  439. except FileNotFoundError:
  440. return
  441. extra = marker = "" # Section-less entries don't have markers.
  442. for line in content.splitlines():
  443. line = line.strip()
  444. if not line or line.startswith("#"): # Comment; ignored.
  445. continue
  446. if line.startswith("[") and line.endswith("]"): # A section header.
  447. extra, _, marker = line.strip("[]").partition(":")
  448. continue
  449. yield RequiresEntry(requirement=line, extra=extra, marker=marker)
  450. def _iter_egg_info_extras(self) -> Iterable[str]:
  451. """Get extras from the egg-info directory."""
  452. known_extras = {""}
  453. for entry in self._iter_requires_txt_entries():
  454. extra = canonicalize_name(entry.extra)
  455. if extra in known_extras:
  456. continue
  457. known_extras.add(extra)
  458. yield extra
  459. def _iter_egg_info_dependencies(self) -> Iterable[str]:
  460. """Get distribution dependencies from the egg-info directory.
  461. To ease parsing, this converts a legacy dependency entry into a PEP 508
  462. requirement string. Like ``_iter_requires_txt_entries()``, there is code
  463. in ``importlib.metadata`` that does mostly the same, but not do exactly
  464. what we need.
  465. Namely, ``importlib.metadata`` does not normalize the extra name before
  466. putting it into the requirement string, which causes marker comparison
  467. to fail because the dist-info format do normalize. This is consistent in
  468. all currently available PEP 517 backends, although not standardized.
  469. """
  470. for entry in self._iter_requires_txt_entries():
  471. extra = canonicalize_name(entry.extra)
  472. if extra and entry.marker:
  473. marker = f'({entry.marker}) and extra == "{extra}"'
  474. elif extra:
  475. marker = f'extra == "{extra}"'
  476. elif entry.marker:
  477. marker = entry.marker
  478. else:
  479. marker = ""
  480. if marker:
  481. yield f"{entry.requirement} ; {marker}"
  482. else:
  483. yield entry.requirement
  484. def _add_egg_info_requires(self, metadata: email.message.Message) -> None:
  485. """Add egg-info requires.txt information to the metadata."""
  486. if not metadata.get_all("Requires-Dist"):
  487. for dep in self._iter_egg_info_dependencies():
  488. metadata["Requires-Dist"] = dep
  489. if not metadata.get_all("Provides-Extra"):
  490. for extra in self._iter_egg_info_extras():
  491. metadata["Provides-Extra"] = extra
  492. class BaseEnvironment:
  493. """An environment containing distributions to introspect."""
  494. @classmethod
  495. def default(cls) -> "BaseEnvironment":
  496. raise NotImplementedError()
  497. @classmethod
  498. def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment":
  499. raise NotImplementedError()
  500. def get_distribution(self, name: str) -> Optional["BaseDistribution"]:
  501. """Given a requirement name, return the installed distributions.
  502. The name may not be normalized. The implementation must canonicalize
  503. it for lookup.
  504. """
  505. raise NotImplementedError()
  506. def _iter_distributions(self) -> Iterator["BaseDistribution"]:
  507. """Iterate through installed distributions.
  508. This function should be implemented by subclass, but never called
  509. directly. Use the public ``iter_distribution()`` instead, which
  510. implements additional logic to make sure the distributions are valid.
  511. """
  512. raise NotImplementedError()
  513. def iter_all_distributions(self) -> Iterator[BaseDistribution]:
  514. """Iterate through all installed distributions without any filtering."""
  515. for dist in self._iter_distributions():
  516. # Make sure the distribution actually comes from a valid Python
  517. # packaging distribution. Pip's AdjacentTempDirectory leaves folders
  518. # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
  519. # valid project name pattern is taken from PEP 508.
  520. project_name_valid = re.match(
  521. r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
  522. dist.canonical_name,
  523. flags=re.IGNORECASE,
  524. )
  525. if not project_name_valid:
  526. logger.warning(
  527. "Ignoring invalid distribution %s (%s)",
  528. dist.canonical_name,
  529. dist.location,
  530. )
  531. continue
  532. yield dist
  533. def iter_installed_distributions(
  534. self,
  535. local_only: bool = True,
  536. skip: Container[str] = stdlib_pkgs,
  537. include_editables: bool = True,
  538. editables_only: bool = False,
  539. user_only: bool = False,
  540. ) -> Iterator[BaseDistribution]:
  541. """Return a list of installed distributions.
  542. This is based on ``iter_all_distributions()`` with additional filtering
  543. options. Note that ``iter_installed_distributions()`` without arguments
  544. is *not* equal to ``iter_all_distributions()``, since some of the
  545. configurations exclude packages by default.
  546. :param local_only: If True (default), only return installations
  547. local to the current virtualenv, if in a virtualenv.
  548. :param skip: An iterable of canonicalized project names to ignore;
  549. defaults to ``stdlib_pkgs``.
  550. :param include_editables: If False, don't report editables.
  551. :param editables_only: If True, only report editables.
  552. :param user_only: If True, only report installations in the user
  553. site directory.
  554. """
  555. it = self.iter_all_distributions()
  556. if local_only:
  557. it = (d for d in it if d.local)
  558. if not include_editables:
  559. it = (d for d in it if not d.editable)
  560. if editables_only:
  561. it = (d for d in it if d.editable)
  562. if user_only:
  563. it = (d for d in it if d.in_usersite)
  564. return (d for d in it if d.canonical_name not in skip)
  565. class Wheel(Protocol):
  566. location: str
  567. def as_zipfile(self) -> zipfile.ZipFile:
  568. raise NotImplementedError()
  569. class FilesystemWheel(Wheel):
  570. def __init__(self, location: str) -> None:
  571. self.location = location
  572. def as_zipfile(self) -> zipfile.ZipFile:
  573. return zipfile.ZipFile(self.location, allowZip64=True)
  574. class MemoryWheel(Wheel):
  575. def __init__(self, location: str, stream: IO[bytes]) -> None:
  576. self.location = location
  577. self.stream = stream
  578. def as_zipfile(self) -> zipfile.ZipFile:
  579. return zipfile.ZipFile(self.stream, allowZip64=True)