PageRenderTime 24ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/env/Lib/site-packages/pip/_internal/index/collector.py

https://gitlab.com/Eightdays/backend
Python | 610 lines | 562 code | 17 blank | 31 comment | 15 complexity | 32d191a70ee1f23cf9213f163dd522d3 MD5 | raw file
  1. """
  2. The main purpose of this module is to expose LinkCollector.collect_sources().
  3. """
  4. import cgi
  5. import collections
  6. import functools
  7. import itertools
  8. import logging
  9. import os
  10. import re
  11. import urllib.parse
  12. import urllib.request
  13. import xml.etree.ElementTree
  14. from html.parser import HTMLParser
  15. from optparse import Values
  16. from typing import (
  17. TYPE_CHECKING,
  18. Callable,
  19. Dict,
  20. Iterable,
  21. List,
  22. MutableMapping,
  23. NamedTuple,
  24. Optional,
  25. Sequence,
  26. Tuple,
  27. Union,
  28. )
  29. from pip._vendor import html5lib, requests
  30. from pip._vendor.requests import Response
  31. from pip._vendor.requests.exceptions import RetryError, SSLError
  32. from pip._internal.exceptions import NetworkConnectionError
  33. from pip._internal.models.link import Link
  34. from pip._internal.models.search_scope import SearchScope
  35. from pip._internal.network.session import PipSession
  36. from pip._internal.network.utils import raise_for_status
  37. from pip._internal.utils.filetypes import is_archive_file
  38. from pip._internal.utils.misc import pairwise, redact_auth_from_url
  39. from pip._internal.vcs import vcs
  40. from .sources import CandidatesFromPage, LinkSource, build_source
  41. if TYPE_CHECKING:
  42. from typing import Protocol
  43. else:
  44. Protocol = object
  45. logger = logging.getLogger(__name__)
  46. HTMLElement = xml.etree.ElementTree.Element
  47. ResponseHeaders = MutableMapping[str, str]
  48. def _match_vcs_scheme(url: str) -> Optional[str]:
  49. """Look for VCS schemes in the URL.
  50. Returns the matched VCS scheme, or None if there's no match.
  51. """
  52. for scheme in vcs.schemes:
  53. if url.lower().startswith(scheme) and url[len(scheme)] in "+:":
  54. return scheme
  55. return None
  56. class _NotHTML(Exception):
  57. def __init__(self, content_type: str, request_desc: str) -> None:
  58. super().__init__(content_type, request_desc)
  59. self.content_type = content_type
  60. self.request_desc = request_desc
  61. def _ensure_html_header(response: Response) -> None:
  62. """Check the Content-Type header to ensure the response contains HTML.
  63. Raises `_NotHTML` if the content type is not text/html.
  64. """
  65. content_type = response.headers.get("Content-Type", "")
  66. if not content_type.lower().startswith("text/html"):
  67. raise _NotHTML(content_type, response.request.method)
  68. class _NotHTTP(Exception):
  69. pass
  70. def _ensure_html_response(url: str, session: PipSession) -> None:
  71. """Send a HEAD request to the URL, and ensure the response contains HTML.
  72. Raises `_NotHTTP` if the URL is not available for a HEAD request, or
  73. `_NotHTML` if the content type is not text/html.
  74. """
  75. scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
  76. if scheme not in {"http", "https"}:
  77. raise _NotHTTP()
  78. resp = session.head(url, allow_redirects=True)
  79. raise_for_status(resp)
  80. _ensure_html_header(resp)
  81. def _get_html_response(url: str, session: PipSession) -> Response:
  82. """Access an HTML page with GET, and return the response.
  83. This consists of three parts:
  84. 1. If the URL looks suspiciously like an archive, send a HEAD first to
  85. check the Content-Type is HTML, to avoid downloading a large file.
  86. Raise `_NotHTTP` if the content type cannot be determined, or
  87. `_NotHTML` if it is not HTML.
  88. 2. Actually perform the request. Raise HTTP exceptions on network failures.
  89. 3. Check the Content-Type header to make sure we got HTML, and raise
  90. `_NotHTML` otherwise.
  91. """
  92. if is_archive_file(Link(url).filename):
  93. _ensure_html_response(url, session=session)
  94. logger.debug("Getting page %s", redact_auth_from_url(url))
  95. resp = session.get(
  96. url,
  97. headers={
  98. "Accept": "text/html",
  99. # We don't want to blindly returned cached data for
  100. # /simple/, because authors generally expecting that
  101. # twine upload && pip install will function, but if
  102. # they've done a pip install in the last ~10 minutes
  103. # it won't. Thus by setting this to zero we will not
  104. # blindly use any cached data, however the benefit of
  105. # using max-age=0 instead of no-cache, is that we will
  106. # still support conditional requests, so we will still
  107. # minimize traffic sent in cases where the page hasn't
  108. # changed at all, we will just always incur the round
  109. # trip for the conditional GET now instead of only
  110. # once per 10 minutes.
  111. # For more information, please see pypa/pip#5670.
  112. "Cache-Control": "max-age=0",
  113. },
  114. )
  115. raise_for_status(resp)
  116. # The check for archives above only works if the url ends with
  117. # something that looks like an archive. However that is not a
  118. # requirement of an url. Unless we issue a HEAD request on every
  119. # url we cannot know ahead of time for sure if something is HTML
  120. # or not. However we can check after we've downloaded it.
  121. _ensure_html_header(resp)
  122. return resp
  123. def _get_encoding_from_headers(headers: ResponseHeaders) -> Optional[str]:
  124. """Determine if we have any encoding information in our headers."""
  125. if headers and "Content-Type" in headers:
  126. content_type, params = cgi.parse_header(headers["Content-Type"])
  127. if "charset" in params:
  128. return params["charset"]
  129. return None
  130. def _determine_base_url(document: HTMLElement, page_url: str) -> str:
  131. """Determine the HTML document's base URL.
  132. This looks for a ``<base>`` tag in the HTML document. If present, its href
  133. attribute denotes the base URL of anchor tags in the document. If there is
  134. no such tag (or if it does not have a valid href attribute), the HTML
  135. file's URL is used as the base URL.
  136. :param document: An HTML document representation. The current
  137. implementation expects the result of ``html5lib.parse()``.
  138. :param page_url: The URL of the HTML document.
  139. TODO: Remove when `html5lib` is dropped.
  140. """
  141. for base in document.findall(".//base"):
  142. href = base.get("href")
  143. if href is not None:
  144. return href
  145. return page_url
  146. def _clean_url_path_part(part: str) -> str:
  147. """
  148. Clean a "part" of a URL path (i.e. after splitting on "@" characters).
  149. """
  150. # We unquote prior to quoting to make sure nothing is double quoted.
  151. return urllib.parse.quote(urllib.parse.unquote(part))
  152. def _clean_file_url_path(part: str) -> str:
  153. """
  154. Clean the first part of a URL path that corresponds to a local
  155. filesystem path (i.e. the first part after splitting on "@" characters).
  156. """
  157. # We unquote prior to quoting to make sure nothing is double quoted.
  158. # Also, on Windows the path part might contain a drive letter which
  159. # should not be quoted. On Linux where drive letters do not
  160. # exist, the colon should be quoted. We rely on urllib.request
  161. # to do the right thing here.
  162. return urllib.request.pathname2url(urllib.request.url2pathname(part))
  163. # percent-encoded: /
  164. _reserved_chars_re = re.compile("(@|%2F)", re.IGNORECASE)
  165. def _clean_url_path(path: str, is_local_path: bool) -> str:
  166. """
  167. Clean the path portion of a URL.
  168. """
  169. if is_local_path:
  170. clean_func = _clean_file_url_path
  171. else:
  172. clean_func = _clean_url_path_part
  173. # Split on the reserved characters prior to cleaning so that
  174. # revision strings in VCS URLs are properly preserved.
  175. parts = _reserved_chars_re.split(path)
  176. cleaned_parts = []
  177. for to_clean, reserved in pairwise(itertools.chain(parts, [""])):
  178. cleaned_parts.append(clean_func(to_clean))
  179. # Normalize %xx escapes (e.g. %2f -> %2F)
  180. cleaned_parts.append(reserved.upper())
  181. return "".join(cleaned_parts)
  182. def _clean_link(url: str) -> str:
  183. """
  184. Make sure a link is fully quoted.
  185. For example, if ' ' occurs in the URL, it will be replaced with "%20",
  186. and without double-quoting other characters.
  187. """
  188. # Split the URL into parts according to the general structure
  189. # `scheme://netloc/path;parameters?query#fragment`.
  190. result = urllib.parse.urlparse(url)
  191. # If the netloc is empty, then the URL refers to a local filesystem path.
  192. is_local_path = not result.netloc
  193. path = _clean_url_path(result.path, is_local_path=is_local_path)
  194. return urllib.parse.urlunparse(result._replace(path=path))
  195. def _create_link_from_element(
  196. element_attribs: Dict[str, Optional[str]],
  197. page_url: str,
  198. base_url: str,
  199. ) -> Optional[Link]:
  200. """
  201. Convert an anchor element's attributes in a simple repository page to a Link.
  202. """
  203. href = element_attribs.get("href")
  204. if not href:
  205. return None
  206. url = _clean_link(urllib.parse.urljoin(base_url, href))
  207. pyrequire = element_attribs.get("data-requires-python")
  208. yanked_reason = element_attribs.get("data-yanked")
  209. link = Link(
  210. url,
  211. comes_from=page_url,
  212. requires_python=pyrequire,
  213. yanked_reason=yanked_reason,
  214. )
  215. return link
  216. class CacheablePageContent:
  217. def __init__(self, page: "HTMLPage") -> None:
  218. assert page.cache_link_parsing
  219. self.page = page
  220. def __eq__(self, other: object) -> bool:
  221. return isinstance(other, type(self)) and self.page.url == other.page.url
  222. def __hash__(self) -> int:
  223. return hash(self.page.url)
  224. class ParseLinks(Protocol):
  225. def __call__(
  226. self, page: "HTMLPage", use_deprecated_html5lib: bool
  227. ) -> Iterable[Link]:
  228. ...
  229. def with_cached_html_pages(fn: ParseLinks) -> ParseLinks:
  230. """
  231. Given a function that parses an Iterable[Link] from an HTMLPage, cache the
  232. function's result (keyed by CacheablePageContent), unless the HTMLPage
  233. `page` has `page.cache_link_parsing == False`.
  234. """
  235. @functools.lru_cache(maxsize=None)
  236. def wrapper(
  237. cacheable_page: CacheablePageContent, use_deprecated_html5lib: bool
  238. ) -> List[Link]:
  239. return list(fn(cacheable_page.page, use_deprecated_html5lib))
  240. @functools.wraps(fn)
  241. def wrapper_wrapper(page: "HTMLPage", use_deprecated_html5lib: bool) -> List[Link]:
  242. if page.cache_link_parsing:
  243. return wrapper(CacheablePageContent(page), use_deprecated_html5lib)
  244. return list(fn(page, use_deprecated_html5lib))
  245. return wrapper_wrapper
  246. def _parse_links_html5lib(page: "HTMLPage") -> Iterable[Link]:
  247. """
  248. Parse an HTML document, and yield its anchor elements as Link objects.
  249. TODO: Remove when `html5lib` is dropped.
  250. """
  251. document = html5lib.parse(
  252. page.content,
  253. transport_encoding=page.encoding,
  254. namespaceHTMLElements=False,
  255. )
  256. url = page.url
  257. base_url = _determine_base_url(document, url)
  258. for anchor in document.findall(".//a"):
  259. link = _create_link_from_element(
  260. anchor.attrib,
  261. page_url=url,
  262. base_url=base_url,
  263. )
  264. if link is None:
  265. continue
  266. yield link
  267. @with_cached_html_pages
  268. def parse_links(page: "HTMLPage", use_deprecated_html5lib: bool) -> Iterable[Link]:
  269. """
  270. Parse an HTML document, and yield its anchor elements as Link objects.
  271. """
  272. if use_deprecated_html5lib:
  273. yield from _parse_links_html5lib(page)
  274. return
  275. parser = HTMLLinkParser(page.url)
  276. encoding = page.encoding or "utf-8"
  277. parser.feed(page.content.decode(encoding))
  278. url = page.url
  279. base_url = parser.base_url or url
  280. for anchor in parser.anchors:
  281. link = _create_link_from_element(
  282. anchor,
  283. page_url=url,
  284. base_url=base_url,
  285. )
  286. if link is None:
  287. continue
  288. yield link
  289. class HTMLPage:
  290. """Represents one page, along with its URL"""
  291. def __init__(
  292. self,
  293. content: bytes,
  294. encoding: Optional[str],
  295. url: str,
  296. cache_link_parsing: bool = True,
  297. ) -> None:
  298. """
  299. :param encoding: the encoding to decode the given content.
  300. :param url: the URL from which the HTML was downloaded.
  301. :param cache_link_parsing: whether links parsed from this page's url
  302. should be cached. PyPI index urls should
  303. have this set to False, for example.
  304. """
  305. self.content = content
  306. self.encoding = encoding
  307. self.url = url
  308. self.cache_link_parsing = cache_link_parsing
  309. def __str__(self) -> str:
  310. return redact_auth_from_url(self.url)
  311. class HTMLLinkParser(HTMLParser):
  312. """
  313. HTMLParser that keeps the first base HREF and a list of all anchor
  314. elements' attributes.
  315. """
  316. def __init__(self, url: str) -> None:
  317. super().__init__(convert_charrefs=True)
  318. self.url: str = url
  319. self.base_url: Optional[str] = None
  320. self.anchors: List[Dict[str, Optional[str]]] = []
  321. def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
  322. if tag == "base" and self.base_url is None:
  323. href = self.get_href(attrs)
  324. if href is not None:
  325. self.base_url = href
  326. elif tag == "a":
  327. self.anchors.append(dict(attrs))
  328. def get_href(self, attrs: List[Tuple[str, Optional[str]]]) -> Optional[str]:
  329. for name, value in attrs:
  330. if name == "href":
  331. return value
  332. return None
  333. def _handle_get_page_fail(
  334. link: Link,
  335. reason: Union[str, Exception],
  336. meth: Optional[Callable[..., None]] = None,
  337. ) -> None:
  338. if meth is None:
  339. meth = logger.debug
  340. meth("Could not fetch URL %s: %s - skipping", link, reason)
  341. def _make_html_page(response: Response, cache_link_parsing: bool = True) -> HTMLPage:
  342. encoding = _get_encoding_from_headers(response.headers)
  343. return HTMLPage(
  344. response.content,
  345. encoding=encoding,
  346. url=response.url,
  347. cache_link_parsing=cache_link_parsing,
  348. )
  349. def _get_html_page(
  350. link: Link, session: Optional[PipSession] = None
  351. ) -> Optional["HTMLPage"]:
  352. if session is None:
  353. raise TypeError(
  354. "_get_html_page() missing 1 required keyword argument: 'session'"
  355. )
  356. url = link.url.split("#", 1)[0]
  357. # Check for VCS schemes that do not support lookup as web pages.
  358. vcs_scheme = _match_vcs_scheme(url)
  359. if vcs_scheme:
  360. logger.warning(
  361. "Cannot look at %s URL %s because it does not support lookup as web pages.",
  362. vcs_scheme,
  363. link,
  364. )
  365. return None
  366. # Tack index.html onto file:// URLs that point to directories
  367. scheme, _, path, _, _, _ = urllib.parse.urlparse(url)
  368. if scheme == "file" and os.path.isdir(urllib.request.url2pathname(path)):
  369. # add trailing slash if not present so urljoin doesn't trim
  370. # final segment
  371. if not url.endswith("/"):
  372. url += "/"
  373. url = urllib.parse.urljoin(url, "index.html")
  374. logger.debug(" file: URL is directory, getting %s", url)
  375. try:
  376. resp = _get_html_response(url, session=session)
  377. except _NotHTTP:
  378. logger.warning(
  379. "Skipping page %s because it looks like an archive, and cannot "
  380. "be checked by a HTTP HEAD request.",
  381. link,
  382. )
  383. except _NotHTML as exc:
  384. logger.warning(
  385. "Skipping page %s because the %s request got Content-Type: %s."
  386. "The only supported Content-Type is text/html",
  387. link,
  388. exc.request_desc,
  389. exc.content_type,
  390. )
  391. except NetworkConnectionError as exc:
  392. _handle_get_page_fail(link, exc)
  393. except RetryError as exc:
  394. _handle_get_page_fail(link, exc)
  395. except SSLError as exc:
  396. reason = "There was a problem confirming the ssl certificate: "
  397. reason += str(exc)
  398. _handle_get_page_fail(link, reason, meth=logger.info)
  399. except requests.ConnectionError as exc:
  400. _handle_get_page_fail(link, f"connection error: {exc}")
  401. except requests.Timeout:
  402. _handle_get_page_fail(link, "timed out")
  403. else:
  404. return _make_html_page(resp, cache_link_parsing=link.cache_link_parsing)
  405. return None
  406. class CollectedSources(NamedTuple):
  407. find_links: Sequence[Optional[LinkSource]]
  408. index_urls: Sequence[Optional[LinkSource]]
  409. class LinkCollector:
  410. """
  411. Responsible for collecting Link objects from all configured locations,
  412. making network requests as needed.
  413. The class's main method is its collect_sources() method.
  414. """
  415. def __init__(
  416. self,
  417. session: PipSession,
  418. search_scope: SearchScope,
  419. ) -> None:
  420. self.search_scope = search_scope
  421. self.session = session
  422. @classmethod
  423. def create(
  424. cls,
  425. session: PipSession,
  426. options: Values,
  427. suppress_no_index: bool = False,
  428. ) -> "LinkCollector":
  429. """
  430. :param session: The Session to use to make requests.
  431. :param suppress_no_index: Whether to ignore the --no-index option
  432. when constructing the SearchScope object.
  433. """
  434. index_urls = [options.index_url] + options.extra_index_urls
  435. if options.no_index and not suppress_no_index:
  436. logger.debug(
  437. "Ignoring indexes: %s",
  438. ",".join(redact_auth_from_url(url) for url in index_urls),
  439. )
  440. index_urls = []
  441. # Make sure find_links is a list before passing to create().
  442. find_links = options.find_links or []
  443. search_scope = SearchScope.create(
  444. find_links=find_links,
  445. index_urls=index_urls,
  446. )
  447. link_collector = LinkCollector(
  448. session=session,
  449. search_scope=search_scope,
  450. )
  451. return link_collector
  452. @property
  453. def find_links(self) -> List[str]:
  454. return self.search_scope.find_links
  455. def fetch_page(self, location: Link) -> Optional[HTMLPage]:
  456. """
  457. Fetch an HTML page containing package links.
  458. """
  459. return _get_html_page(location, session=self.session)
  460. def collect_sources(
  461. self,
  462. project_name: str,
  463. candidates_from_page: CandidatesFromPage,
  464. ) -> CollectedSources:
  465. # The OrderedDict calls deduplicate sources by URL.
  466. index_url_sources = collections.OrderedDict(
  467. build_source(
  468. loc,
  469. candidates_from_page=candidates_from_page,
  470. page_validator=self.session.is_secure_origin,
  471. expand_dir=False,
  472. cache_link_parsing=False,
  473. )
  474. for loc in self.search_scope.get_index_urls_locations(project_name)
  475. ).values()
  476. find_links_sources = collections.OrderedDict(
  477. build_source(
  478. loc,
  479. candidates_from_page=candidates_from_page,
  480. page_validator=self.session.is_secure_origin,
  481. expand_dir=True,
  482. cache_link_parsing=True,
  483. )
  484. for loc in self.find_links
  485. ).values()
  486. if logger.isEnabledFor(logging.DEBUG):
  487. lines = [
  488. f"* {s.link}"
  489. for s in itertools.chain(find_links_sources, index_url_sources)
  490. if s is not None and s.link is not None
  491. ]
  492. lines = [
  493. f"{len(lines)} location(s) to search "
  494. f"for versions of {project_name}:"
  495. ] + lines
  496. logger.debug("\n".join(lines))
  497. return CollectedSources(
  498. find_links=list(find_links_sources),
  499. index_urls=list(index_url_sources),
  500. )