PageRenderTime 26ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

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

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