link.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import functools
  2. import logging
  3. import os
  4. import posixpath
  5. import re
  6. import urllib.parse
  7. from typing import (
  8. TYPE_CHECKING,
  9. Dict,
  10. List,
  11. Mapping,
  12. NamedTuple,
  13. Optional,
  14. Tuple,
  15. Union,
  16. )
  17. from pip._internal.utils.filetypes import WHEEL_EXTENSION
  18. from pip._internal.utils.hashes import Hashes
  19. from pip._internal.utils.misc import (
  20. redact_auth_from_url,
  21. split_auth_from_netloc,
  22. splitext,
  23. )
  24. from pip._internal.utils.models import KeyBasedCompareMixin
  25. from pip._internal.utils.urls import path_to_url, url_to_path
  26. if TYPE_CHECKING:
  27. from pip._internal.index.collector import IndexContent
  28. logger = logging.getLogger(__name__)
  29. # Order matters, earlier hashes have a precedence over later hashes for what
  30. # we will pick to use.
  31. _SUPPORTED_HASHES = ("sha512", "sha384", "sha256", "sha224", "sha1", "md5")
  32. class Link(KeyBasedCompareMixin):
  33. """Represents a parsed link from a Package Index's simple URL"""
  34. __slots__ = [
  35. "_parsed_url",
  36. "_url",
  37. "_hashes",
  38. "comes_from",
  39. "requires_python",
  40. "yanked_reason",
  41. "cache_link_parsing",
  42. ]
  43. def __init__(
  44. self,
  45. url: str,
  46. comes_from: Optional[Union[str, "IndexContent"]] = None,
  47. requires_python: Optional[str] = None,
  48. yanked_reason: Optional[str] = None,
  49. cache_link_parsing: bool = True,
  50. hashes: Optional[Mapping[str, str]] = None,
  51. ) -> None:
  52. """
  53. :param url: url of the resource pointed to (href of the link)
  54. :param comes_from: instance of IndexContent where the link was found,
  55. or string.
  56. :param requires_python: String containing the `Requires-Python`
  57. metadata field, specified in PEP 345. This may be specified by
  58. a data-requires-python attribute in the HTML link tag, as
  59. described in PEP 503.
  60. :param yanked_reason: the reason the file has been yanked, if the
  61. file has been yanked, or None if the file hasn't been yanked.
  62. This is the value of the "data-yanked" attribute, if present, in
  63. a simple repository HTML link. If the file has been yanked but
  64. no reason was provided, this should be the empty string. See
  65. PEP 592 for more information and the specification.
  66. :param cache_link_parsing: A flag that is used elsewhere to determine
  67. whether resources retrieved from this link
  68. should be cached. PyPI index urls should
  69. generally have this set to False, for
  70. example.
  71. :param hashes: A mapping of hash names to digests to allow us to
  72. determine the validity of a download.
  73. """
  74. # url can be a UNC windows share
  75. if url.startswith("\\\\"):
  76. url = path_to_url(url)
  77. self._parsed_url = urllib.parse.urlsplit(url)
  78. # Store the url as a private attribute to prevent accidentally
  79. # trying to set a new value.
  80. self._url = url
  81. self._hashes = hashes if hashes is not None else {}
  82. self.comes_from = comes_from
  83. self.requires_python = requires_python if requires_python else None
  84. self.yanked_reason = yanked_reason
  85. super().__init__(key=url, defining_class=Link)
  86. self.cache_link_parsing = cache_link_parsing
  87. def __str__(self) -> str:
  88. if self.requires_python:
  89. rp = f" (requires-python:{self.requires_python})"
  90. else:
  91. rp = ""
  92. if self.comes_from:
  93. return "{} (from {}){}".format(
  94. redact_auth_from_url(self._url), self.comes_from, rp
  95. )
  96. else:
  97. return redact_auth_from_url(str(self._url))
  98. def __repr__(self) -> str:
  99. return f"<Link {self}>"
  100. @property
  101. def url(self) -> str:
  102. return self._url
  103. @property
  104. def filename(self) -> str:
  105. path = self.path.rstrip("/")
  106. name = posixpath.basename(path)
  107. if not name:
  108. # Make sure we don't leak auth information if the netloc
  109. # includes a username and password.
  110. netloc, user_pass = split_auth_from_netloc(self.netloc)
  111. return netloc
  112. name = urllib.parse.unquote(name)
  113. assert name, f"URL {self._url!r} produced no filename"
  114. return name
  115. @property
  116. def file_path(self) -> str:
  117. return url_to_path(self.url)
  118. @property
  119. def scheme(self) -> str:
  120. return self._parsed_url.scheme
  121. @property
  122. def netloc(self) -> str:
  123. """
  124. This can contain auth information.
  125. """
  126. return self._parsed_url.netloc
  127. @property
  128. def path(self) -> str:
  129. return urllib.parse.unquote(self._parsed_url.path)
  130. def splitext(self) -> Tuple[str, str]:
  131. return splitext(posixpath.basename(self.path.rstrip("/")))
  132. @property
  133. def ext(self) -> str:
  134. return self.splitext()[1]
  135. @property
  136. def url_without_fragment(self) -> str:
  137. scheme, netloc, path, query, fragment = self._parsed_url
  138. return urllib.parse.urlunsplit((scheme, netloc, path, query, ""))
  139. _egg_fragment_re = re.compile(r"[#&]egg=([^&]*)")
  140. @property
  141. def egg_fragment(self) -> Optional[str]:
  142. match = self._egg_fragment_re.search(self._url)
  143. if not match:
  144. return None
  145. return match.group(1)
  146. _subdirectory_fragment_re = re.compile(r"[#&]subdirectory=([^&]*)")
  147. @property
  148. def subdirectory_fragment(self) -> Optional[str]:
  149. match = self._subdirectory_fragment_re.search(self._url)
  150. if not match:
  151. return None
  152. return match.group(1)
  153. _hash_re = re.compile(
  154. r"({choices})=([a-f0-9]+)".format(choices="|".join(_SUPPORTED_HASHES))
  155. )
  156. @property
  157. def hash(self) -> Optional[str]:
  158. for hashname in _SUPPORTED_HASHES:
  159. if hashname in self._hashes:
  160. return self._hashes[hashname]
  161. match = self._hash_re.search(self._url)
  162. if match:
  163. return match.group(2)
  164. return None
  165. @property
  166. def hash_name(self) -> Optional[str]:
  167. for hashname in _SUPPORTED_HASHES:
  168. if hashname in self._hashes:
  169. return hashname
  170. match = self._hash_re.search(self._url)
  171. if match:
  172. return match.group(1)
  173. return None
  174. @property
  175. def show_url(self) -> str:
  176. return posixpath.basename(self._url.split("#", 1)[0].split("?", 1)[0])
  177. @property
  178. def is_file(self) -> bool:
  179. return self.scheme == "file"
  180. def is_existing_dir(self) -> bool:
  181. return self.is_file and os.path.isdir(self.file_path)
  182. @property
  183. def is_wheel(self) -> bool:
  184. return self.ext == WHEEL_EXTENSION
  185. @property
  186. def is_vcs(self) -> bool:
  187. from pip._internal.vcs import vcs
  188. return self.scheme in vcs.all_schemes
  189. @property
  190. def is_yanked(self) -> bool:
  191. return self.yanked_reason is not None
  192. @property
  193. def has_hash(self) -> bool:
  194. return self.hash_name is not None
  195. def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:
  196. """
  197. Return True if the link has a hash and it is allowed.
  198. """
  199. if hashes is None or not self.has_hash:
  200. return False
  201. # Assert non-None so mypy knows self.hash_name and self.hash are str.
  202. assert self.hash_name is not None
  203. assert self.hash is not None
  204. return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash)
  205. class _CleanResult(NamedTuple):
  206. """Convert link for equivalency check.
  207. This is used in the resolver to check whether two URL-specified requirements
  208. likely point to the same distribution and can be considered equivalent. This
  209. equivalency logic avoids comparing URLs literally, which can be too strict
  210. (e.g. "a=1&b=2" vs "b=2&a=1") and produce conflicts unexpecting to users.
  211. Currently this does three things:
  212. 1. Drop the basic auth part. This is technically wrong since a server can
  213. serve different content based on auth, but if it does that, it is even
  214. impossible to guarantee two URLs without auth are equivalent, since
  215. the user can input different auth information when prompted. So the
  216. practical solution is to assume the auth doesn't affect the response.
  217. 2. Parse the query to avoid the ordering issue. Note that ordering under the
  218. same key in the query are NOT cleaned; i.e. "a=1&a=2" and "a=2&a=1" are
  219. still considered different.
  220. 3. Explicitly drop most of the fragment part, except ``subdirectory=`` and
  221. hash values, since it should have no impact the downloaded content. Note
  222. that this drops the "egg=" part historically used to denote the requested
  223. project (and extras), which is wrong in the strictest sense, but too many
  224. people are supplying it inconsistently to cause superfluous resolution
  225. conflicts, so we choose to also ignore them.
  226. """
  227. parsed: urllib.parse.SplitResult
  228. query: Dict[str, List[str]]
  229. subdirectory: str
  230. hashes: Dict[str, str]
  231. def _clean_link(link: Link) -> _CleanResult:
  232. parsed = link._parsed_url
  233. netloc = parsed.netloc.rsplit("@", 1)[-1]
  234. # According to RFC 8089, an empty host in file: means localhost.
  235. if parsed.scheme == "file" and not netloc:
  236. netloc = "localhost"
  237. fragment = urllib.parse.parse_qs(parsed.fragment)
  238. if "egg" in fragment:
  239. logger.debug("Ignoring egg= fragment in %s", link)
  240. try:
  241. # If there are multiple subdirectory values, use the first one.
  242. # This matches the behavior of Link.subdirectory_fragment.
  243. subdirectory = fragment["subdirectory"][0]
  244. except (IndexError, KeyError):
  245. subdirectory = ""
  246. # If there are multiple hash values under the same algorithm, use the
  247. # first one. This matches the behavior of Link.hash_value.
  248. hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment}
  249. return _CleanResult(
  250. parsed=parsed._replace(netloc=netloc, query="", fragment=""),
  251. query=urllib.parse.parse_qs(parsed.query),
  252. subdirectory=subdirectory,
  253. hashes=hashes,
  254. )
  255. @functools.lru_cache(maxsize=None)
  256. def links_equivalent(link1: Link, link2: Link) -> bool:
  257. return _clean_link(link1) == _clean_link(link2)