link.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import os
  2. import posixpath
  3. import re
  4. from pip._vendor.six.moves.urllib import parse as urllib_parse
  5. from pip._internal.utils.filetypes import WHEEL_EXTENSION
  6. from pip._internal.utils.misc import (
  7. redact_auth_from_url,
  8. split_auth_from_netloc,
  9. splitext,
  10. )
  11. from pip._internal.utils.models import KeyBasedCompareMixin
  12. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  13. from pip._internal.utils.urls import path_to_url, url_to_path
  14. if MYPY_CHECK_RUNNING:
  15. from typing import Optional, Text, Tuple, Union
  16. from pip._internal.index.collector import HTMLPage
  17. from pip._internal.utils.hashes import Hashes
  18. class Link(KeyBasedCompareMixin):
  19. """Represents a parsed link from a Package Index's simple URL
  20. """
  21. def __init__(
  22. self,
  23. url, # type: str
  24. comes_from=None, # type: Optional[Union[str, HTMLPage]]
  25. requires_python=None, # type: Optional[str]
  26. yanked_reason=None, # type: Optional[Text]
  27. cache_link_parsing=True, # type: bool
  28. ):
  29. # type: (...) -> None
  30. """
  31. :param url: url of the resource pointed to (href of the link)
  32. :param comes_from: instance of HTMLPage where the link was found,
  33. or string.
  34. :param requires_python: String containing the `Requires-Python`
  35. metadata field, specified in PEP 345. This may be specified by
  36. a data-requires-python attribute in the HTML link tag, as
  37. described in PEP 503.
  38. :param yanked_reason: the reason the file has been yanked, if the
  39. file has been yanked, or None if the file hasn't been yanked.
  40. This is the value of the "data-yanked" attribute, if present, in
  41. a simple repository HTML link. If the file has been yanked but
  42. no reason was provided, this should be the empty string. See
  43. PEP 592 for more information and the specification.
  44. :param cache_link_parsing: A flag that is used elsewhere to determine
  45. whether resources retrieved from this link
  46. should be cached. PyPI index urls should
  47. generally have this set to False, for
  48. example.
  49. """
  50. # url can be a UNC windows share
  51. if url.startswith('\\\\'):
  52. url = path_to_url(url)
  53. self._parsed_url = urllib_parse.urlsplit(url)
  54. # Store the url as a private attribute to prevent accidentally
  55. # trying to set a new value.
  56. self._url = url
  57. self.comes_from = comes_from
  58. self.requires_python = requires_python if requires_python else None
  59. self.yanked_reason = yanked_reason
  60. super(Link, self).__init__(key=url, defining_class=Link)
  61. self.cache_link_parsing = cache_link_parsing
  62. def __str__(self):
  63. # type: () -> str
  64. if self.requires_python:
  65. rp = ' (requires-python:{})'.format(self.requires_python)
  66. else:
  67. rp = ''
  68. if self.comes_from:
  69. return '{} (from {}){}'.format(
  70. redact_auth_from_url(self._url), self.comes_from, rp)
  71. else:
  72. return redact_auth_from_url(str(self._url))
  73. def __repr__(self):
  74. # type: () -> str
  75. return '<Link {}>'.format(self)
  76. @property
  77. def url(self):
  78. # type: () -> str
  79. return self._url
  80. @property
  81. def filename(self):
  82. # type: () -> str
  83. path = self.path.rstrip('/')
  84. name = posixpath.basename(path)
  85. if not name:
  86. # Make sure we don't leak auth information if the netloc
  87. # includes a username and password.
  88. netloc, user_pass = split_auth_from_netloc(self.netloc)
  89. return netloc
  90. name = urllib_parse.unquote(name)
  91. assert name, (
  92. 'URL {self._url!r} produced no filename'.format(**locals()))
  93. return name
  94. @property
  95. def file_path(self):
  96. # type: () -> str
  97. return url_to_path(self.url)
  98. @property
  99. def scheme(self):
  100. # type: () -> str
  101. return self._parsed_url.scheme
  102. @property
  103. def netloc(self):
  104. # type: () -> str
  105. """
  106. This can contain auth information.
  107. """
  108. return self._parsed_url.netloc
  109. @property
  110. def path(self):
  111. # type: () -> str
  112. return urllib_parse.unquote(self._parsed_url.path)
  113. def splitext(self):
  114. # type: () -> Tuple[str, str]
  115. return splitext(posixpath.basename(self.path.rstrip('/')))
  116. @property
  117. def ext(self):
  118. # type: () -> str
  119. return self.splitext()[1]
  120. @property
  121. def url_without_fragment(self):
  122. # type: () -> str
  123. scheme, netloc, path, query, fragment = self._parsed_url
  124. return urllib_parse.urlunsplit((scheme, netloc, path, query, None))
  125. _egg_fragment_re = re.compile(r'[#&]egg=([^&]*)')
  126. @property
  127. def egg_fragment(self):
  128. # type: () -> Optional[str]
  129. match = self._egg_fragment_re.search(self._url)
  130. if not match:
  131. return None
  132. return match.group(1)
  133. _subdirectory_fragment_re = re.compile(r'[#&]subdirectory=([^&]*)')
  134. @property
  135. def subdirectory_fragment(self):
  136. # type: () -> Optional[str]
  137. match = self._subdirectory_fragment_re.search(self._url)
  138. if not match:
  139. return None
  140. return match.group(1)
  141. _hash_re = re.compile(
  142. r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)'
  143. )
  144. @property
  145. def hash(self):
  146. # type: () -> Optional[str]
  147. match = self._hash_re.search(self._url)
  148. if match:
  149. return match.group(2)
  150. return None
  151. @property
  152. def hash_name(self):
  153. # type: () -> Optional[str]
  154. match = self._hash_re.search(self._url)
  155. if match:
  156. return match.group(1)
  157. return None
  158. @property
  159. def show_url(self):
  160. # type: () -> str
  161. return posixpath.basename(self._url.split('#', 1)[0].split('?', 1)[0])
  162. @property
  163. def is_file(self):
  164. # type: () -> bool
  165. return self.scheme == 'file'
  166. def is_existing_dir(self):
  167. # type: () -> bool
  168. return self.is_file and os.path.isdir(self.file_path)
  169. @property
  170. def is_wheel(self):
  171. # type: () -> bool
  172. return self.ext == WHEEL_EXTENSION
  173. @property
  174. def is_vcs(self):
  175. # type: () -> bool
  176. from pip._internal.vcs import vcs
  177. return self.scheme in vcs.all_schemes
  178. @property
  179. def is_yanked(self):
  180. # type: () -> bool
  181. return self.yanked_reason is not None
  182. @property
  183. def has_hash(self):
  184. # type: () -> bool
  185. return self.hash_name is not None
  186. def is_hash_allowed(self, hashes):
  187. # type: (Optional[Hashes]) -> bool
  188. """
  189. Return True if the link has a hash and it is allowed.
  190. """
  191. if hashes is None or not self.has_hash:
  192. return False
  193. # Assert non-None so mypy knows self.hash_name and self.hash are str.
  194. assert self.hash_name is not None
  195. assert self.hash is not None
  196. return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash)