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.

index.py 37KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. """Routines related to PyPI, indexes"""
  2. from __future__ import absolute_import
  3. import cgi
  4. import itertools
  5. import logging
  6. import mimetypes
  7. import os
  8. import posixpath
  9. import re
  10. import sys
  11. from collections import namedtuple
  12. from pip._vendor import html5lib, requests, six
  13. from pip._vendor.distlib.compat import unescape
  14. from pip._vendor.packaging import specifiers
  15. from pip._vendor.packaging.utils import canonicalize_name
  16. from pip._vendor.packaging.version import parse as parse_version
  17. from pip._vendor.requests.exceptions import RetryError, SSLError
  18. from pip._vendor.six.moves.urllib import parse as urllib_parse
  19. from pip._vendor.six.moves.urllib import request as urllib_request
  20. from pip._internal.download import HAS_TLS, is_url, path_to_url, url_to_path
  21. from pip._internal.exceptions import (
  22. BestVersionAlreadyInstalled, DistributionNotFound, InvalidWheelFilename,
  23. UnsupportedWheel,
  24. )
  25. from pip._internal.models.candidate import InstallationCandidate
  26. from pip._internal.models.format_control import FormatControl
  27. from pip._internal.models.index import PyPI
  28. from pip._internal.models.link import Link
  29. from pip._internal.pep425tags import get_supported
  30. from pip._internal.utils.compat import ipaddress
  31. from pip._internal.utils.logging import indent_log
  32. from pip._internal.utils.misc import (
  33. ARCHIVE_EXTENSIONS, SUPPORTED_EXTENSIONS, WHEEL_EXTENSION, normalize_path,
  34. redact_password_from_url,
  35. )
  36. from pip._internal.utils.packaging import check_requires_python
  37. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  38. from pip._internal.wheel import Wheel
  39. if MYPY_CHECK_RUNNING:
  40. from logging import Logger # noqa: F401
  41. from typing import ( # noqa: F401
  42. Tuple, Optional, Any, List, Union, Callable, Set, Sequence,
  43. Iterable, MutableMapping
  44. )
  45. from pip._vendor.packaging.version import _BaseVersion # noqa: F401
  46. from pip._vendor.requests import Response # noqa: F401
  47. from pip._internal.req import InstallRequirement # noqa: F401
  48. from pip._internal.download import PipSession # noqa: F401
  49. SecureOrigin = Tuple[str, str, Optional[str]]
  50. BuildTag = Tuple[Any, ...] # either emply tuple or Tuple[int, str]
  51. CandidateSortingKey = Tuple[int, _BaseVersion, BuildTag, Optional[int]]
  52. __all__ = ['FormatControl', 'PackageFinder']
  53. SECURE_ORIGINS = [
  54. # protocol, hostname, port
  55. # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)
  56. ("https", "*", "*"),
  57. ("*", "localhost", "*"),
  58. ("*", "127.0.0.0/8", "*"),
  59. ("*", "::1/128", "*"),
  60. ("file", "*", None),
  61. # ssh is always secure.
  62. ("ssh", "*", "*"),
  63. ] # type: List[SecureOrigin]
  64. logger = logging.getLogger(__name__)
  65. def _match_vcs_scheme(url):
  66. # type: (str) -> Optional[str]
  67. """Look for VCS schemes in the URL.
  68. Returns the matched VCS scheme, or None if there's no match.
  69. """
  70. from pip._internal.vcs import VcsSupport
  71. for scheme in VcsSupport.schemes:
  72. if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
  73. return scheme
  74. return None
  75. def _is_url_like_archive(url):
  76. # type: (str) -> bool
  77. """Return whether the URL looks like an archive.
  78. """
  79. filename = Link(url).filename
  80. for bad_ext in ARCHIVE_EXTENSIONS:
  81. if filename.endswith(bad_ext):
  82. return True
  83. return False
  84. class _NotHTML(Exception):
  85. def __init__(self, content_type, request_desc):
  86. # type: (str, str) -> None
  87. super(_NotHTML, self).__init__(content_type, request_desc)
  88. self.content_type = content_type
  89. self.request_desc = request_desc
  90. def _ensure_html_header(response):
  91. # type: (Response) -> None
  92. """Check the Content-Type header to ensure the response contains HTML.
  93. Raises `_NotHTML` if the content type is not text/html.
  94. """
  95. content_type = response.headers.get("Content-Type", "")
  96. if not content_type.lower().startswith("text/html"):
  97. raise _NotHTML(content_type, response.request.method)
  98. class _NotHTTP(Exception):
  99. pass
  100. def _ensure_html_response(url, session):
  101. # type: (str, PipSession) -> None
  102. """Send a HEAD request to the URL, and ensure the response contains HTML.
  103. Raises `_NotHTTP` if the URL is not available for a HEAD request, or
  104. `_NotHTML` if the content type is not text/html.
  105. """
  106. scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
  107. if scheme not in {'http', 'https'}:
  108. raise _NotHTTP()
  109. resp = session.head(url, allow_redirects=True)
  110. resp.raise_for_status()
  111. _ensure_html_header(resp)
  112. def _get_html_response(url, session):
  113. # type: (str, PipSession) -> Response
  114. """Access an HTML page with GET, and return the response.
  115. This consists of three parts:
  116. 1. If the URL looks suspiciously like an archive, send a HEAD first to
  117. check the Content-Type is HTML, to avoid downloading a large file.
  118. Raise `_NotHTTP` if the content type cannot be determined, or
  119. `_NotHTML` if it is not HTML.
  120. 2. Actually perform the request. Raise HTTP exceptions on network failures.
  121. 3. Check the Content-Type header to make sure we got HTML, and raise
  122. `_NotHTML` otherwise.
  123. """
  124. if _is_url_like_archive(url):
  125. _ensure_html_response(url, session=session)
  126. logger.debug('Getting page %s', url)
  127. resp = session.get(
  128. url,
  129. headers={
  130. "Accept": "text/html",
  131. # We don't want to blindly returned cached data for
  132. # /simple/, because authors generally expecting that
  133. # twine upload && pip install will function, but if
  134. # they've done a pip install in the last ~10 minutes
  135. # it won't. Thus by setting this to zero we will not
  136. # blindly use any cached data, however the benefit of
  137. # using max-age=0 instead of no-cache, is that we will
  138. # still support conditional requests, so we will still
  139. # minimize traffic sent in cases where the page hasn't
  140. # changed at all, we will just always incur the round
  141. # trip for the conditional GET now instead of only
  142. # once per 10 minutes.
  143. # For more information, please see pypa/pip#5670.
  144. "Cache-Control": "max-age=0",
  145. },
  146. )
  147. resp.raise_for_status()
  148. # The check for archives above only works if the url ends with
  149. # something that looks like an archive. However that is not a
  150. # requirement of an url. Unless we issue a HEAD request on every
  151. # url we cannot know ahead of time for sure if something is HTML
  152. # or not. However we can check after we've downloaded it.
  153. _ensure_html_header(resp)
  154. return resp
  155. def _handle_get_page_fail(
  156. link, # type: Link
  157. reason, # type: Union[str, Exception]
  158. meth=None # type: Optional[Callable[..., None]]
  159. ):
  160. # type: (...) -> None
  161. if meth is None:
  162. meth = logger.debug
  163. meth("Could not fetch URL %s: %s - skipping", link, reason)
  164. def _get_html_page(link, session=None):
  165. # type: (Link, Optional[PipSession]) -> Optional[HTMLPage]
  166. if session is None:
  167. raise TypeError(
  168. "_get_html_page() missing 1 required keyword argument: 'session'"
  169. )
  170. url = link.url.split('#', 1)[0]
  171. # Check for VCS schemes that do not support lookup as web pages.
  172. vcs_scheme = _match_vcs_scheme(url)
  173. if vcs_scheme:
  174. logger.debug('Cannot look at %s URL %s', vcs_scheme, link)
  175. return None
  176. # Tack index.html onto file:// URLs that point to directories
  177. scheme, _, path, _, _, _ = urllib_parse.urlparse(url)
  178. if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))):
  179. # add trailing slash if not present so urljoin doesn't trim
  180. # final segment
  181. if not url.endswith('/'):
  182. url += '/'
  183. url = urllib_parse.urljoin(url, 'index.html')
  184. logger.debug(' file: URL is directory, getting %s', url)
  185. try:
  186. resp = _get_html_response(url, session=session)
  187. except _NotHTTP as exc:
  188. logger.debug(
  189. 'Skipping page %s because it looks like an archive, and cannot '
  190. 'be checked by HEAD.', link,
  191. )
  192. except _NotHTML as exc:
  193. logger.debug(
  194. 'Skipping page %s because the %s request got Content-Type: %s',
  195. link, exc.request_desc, exc.content_type,
  196. )
  197. except requests.HTTPError as exc:
  198. _handle_get_page_fail(link, exc)
  199. except RetryError as exc:
  200. _handle_get_page_fail(link, exc)
  201. except SSLError as exc:
  202. reason = "There was a problem confirming the ssl certificate: "
  203. reason += str(exc)
  204. _handle_get_page_fail(link, reason, meth=logger.info)
  205. except requests.ConnectionError as exc:
  206. _handle_get_page_fail(link, "connection error: %s" % exc)
  207. except requests.Timeout:
  208. _handle_get_page_fail(link, "timed out")
  209. else:
  210. return HTMLPage(resp.content, resp.url, resp.headers)
  211. return None
  212. class PackageFinder(object):
  213. """This finds packages.
  214. This is meant to match easy_install's technique for looking for
  215. packages, by reading pages and looking for appropriate links.
  216. """
  217. def __init__(
  218. self,
  219. find_links, # type: List[str]
  220. index_urls, # type: List[str]
  221. allow_all_prereleases=False, # type: bool
  222. trusted_hosts=None, # type: Optional[Iterable[str]]
  223. session=None, # type: Optional[PipSession]
  224. format_control=None, # type: Optional[FormatControl]
  225. platform=None, # type: Optional[str]
  226. versions=None, # type: Optional[List[str]]
  227. abi=None, # type: Optional[str]
  228. implementation=None, # type: Optional[str]
  229. prefer_binary=False # type: bool
  230. ):
  231. # type: (...) -> None
  232. """Create a PackageFinder.
  233. :param format_control: A FormatControl object or None. Used to control
  234. the selection of source packages / binary packages when consulting
  235. the index and links.
  236. :param platform: A string or None. If None, searches for packages
  237. that are supported by the current system. Otherwise, will find
  238. packages that can be built on the platform passed in. These
  239. packages will only be downloaded for distribution: they will
  240. not be built locally.
  241. :param versions: A list of strings or None. This is passed directly
  242. to pep425tags.py in the get_supported() method.
  243. :param abi: A string or None. This is passed directly
  244. to pep425tags.py in the get_supported() method.
  245. :param implementation: A string or None. This is passed directly
  246. to pep425tags.py in the get_supported() method.
  247. """
  248. if session is None:
  249. raise TypeError(
  250. "PackageFinder() missing 1 required keyword argument: "
  251. "'session'"
  252. )
  253. # Build find_links. If an argument starts with ~, it may be
  254. # a local file relative to a home directory. So try normalizing
  255. # it and if it exists, use the normalized version.
  256. # This is deliberately conservative - it might be fine just to
  257. # blindly normalize anything starting with a ~...
  258. self.find_links = [] # type: List[str]
  259. for link in find_links:
  260. if link.startswith('~'):
  261. new_link = normalize_path(link)
  262. if os.path.exists(new_link):
  263. link = new_link
  264. self.find_links.append(link)
  265. self.index_urls = index_urls
  266. # These are boring links that have already been logged somehow:
  267. self.logged_links = set() # type: Set[Link]
  268. self.format_control = format_control or FormatControl(set(), set())
  269. # Domains that we won't emit warnings for when not using HTTPS
  270. self.secure_origins = [
  271. ("*", host, "*")
  272. for host in (trusted_hosts if trusted_hosts else [])
  273. ] # type: List[SecureOrigin]
  274. # Do we want to allow _all_ pre-releases?
  275. self.allow_all_prereleases = allow_all_prereleases
  276. # The Session we'll use to make requests
  277. self.session = session
  278. # The valid tags to check potential found wheel candidates against
  279. self.valid_tags = get_supported(
  280. versions=versions,
  281. platform=platform,
  282. abi=abi,
  283. impl=implementation,
  284. )
  285. # Do we prefer old, but valid, binary dist over new source dist
  286. self.prefer_binary = prefer_binary
  287. # If we don't have TLS enabled, then WARN if anyplace we're looking
  288. # relies on TLS.
  289. if not HAS_TLS:
  290. for link in itertools.chain(self.index_urls, self.find_links):
  291. parsed = urllib_parse.urlparse(link)
  292. if parsed.scheme == "https":
  293. logger.warning(
  294. "pip is configured with locations that require "
  295. "TLS/SSL, however the ssl module in Python is not "
  296. "available."
  297. )
  298. break
  299. def get_formatted_locations(self):
  300. # type: () -> str
  301. lines = []
  302. if self.index_urls and self.index_urls != [PyPI.simple_url]:
  303. lines.append(
  304. "Looking in indexes: {}".format(", ".join(
  305. redact_password_from_url(url) for url in self.index_urls))
  306. )
  307. if self.find_links:
  308. lines.append(
  309. "Looking in links: {}".format(", ".join(self.find_links))
  310. )
  311. return "\n".join(lines)
  312. @staticmethod
  313. def _sort_locations(locations, expand_dir=False):
  314. # type: (Sequence[str], bool) -> Tuple[List[str], List[str]]
  315. """
  316. Sort locations into "files" (archives) and "urls", and return
  317. a pair of lists (files,urls)
  318. """
  319. files = []
  320. urls = []
  321. # puts the url for the given file path into the appropriate list
  322. def sort_path(path):
  323. url = path_to_url(path)
  324. if mimetypes.guess_type(url, strict=False)[0] == 'text/html':
  325. urls.append(url)
  326. else:
  327. files.append(url)
  328. for url in locations:
  329. is_local_path = os.path.exists(url)
  330. is_file_url = url.startswith('file:')
  331. if is_local_path or is_file_url:
  332. if is_local_path:
  333. path = url
  334. else:
  335. path = url_to_path(url)
  336. if os.path.isdir(path):
  337. if expand_dir:
  338. path = os.path.realpath(path)
  339. for item in os.listdir(path):
  340. sort_path(os.path.join(path, item))
  341. elif is_file_url:
  342. urls.append(url)
  343. else:
  344. logger.warning(
  345. "Path '{0}' is ignored: "
  346. "it is a directory.".format(path),
  347. )
  348. elif os.path.isfile(path):
  349. sort_path(path)
  350. else:
  351. logger.warning(
  352. "Url '%s' is ignored: it is neither a file "
  353. "nor a directory.", url,
  354. )
  355. elif is_url(url):
  356. # Only add url with clear scheme
  357. urls.append(url)
  358. else:
  359. logger.warning(
  360. "Url '%s' is ignored. It is either a non-existing "
  361. "path or lacks a specific scheme.", url,
  362. )
  363. return files, urls
  364. def _candidate_sort_key(self, candidate):
  365. # type: (InstallationCandidate) -> CandidateSortingKey
  366. """
  367. Function used to generate link sort key for link tuples.
  368. The greater the return value, the more preferred it is.
  369. If not finding wheels, then sorted by version only.
  370. If finding wheels, then the sort order is by version, then:
  371. 1. existing installs
  372. 2. wheels ordered via Wheel.support_index_min(self.valid_tags)
  373. 3. source archives
  374. If prefer_binary was set, then all wheels are sorted above sources.
  375. Note: it was considered to embed this logic into the Link
  376. comparison operators, but then different sdist links
  377. with the same version, would have to be considered equal
  378. """
  379. support_num = len(self.valid_tags)
  380. build_tag = tuple() # type: BuildTag
  381. binary_preference = 0
  382. if candidate.location.is_wheel:
  383. # can raise InvalidWheelFilename
  384. wheel = Wheel(candidate.location.filename)
  385. if not wheel.supported(self.valid_tags):
  386. raise UnsupportedWheel(
  387. "%s is not a supported wheel for this platform. It "
  388. "can't be sorted." % wheel.filename
  389. )
  390. if self.prefer_binary:
  391. binary_preference = 1
  392. pri = -(wheel.support_index_min(self.valid_tags))
  393. if wheel.build_tag is not None:
  394. match = re.match(r'^(\d+)(.*)$', wheel.build_tag)
  395. build_tag_groups = match.groups()
  396. build_tag = (int(build_tag_groups[0]), build_tag_groups[1])
  397. else: # sdist
  398. pri = -(support_num)
  399. return (binary_preference, candidate.version, build_tag, pri)
  400. def _validate_secure_origin(self, logger, location):
  401. # type: (Logger, Link) -> bool
  402. # Determine if this url used a secure transport mechanism
  403. parsed = urllib_parse.urlparse(str(location))
  404. origin = (parsed.scheme, parsed.hostname, parsed.port)
  405. # The protocol to use to see if the protocol matches.
  406. # Don't count the repository type as part of the protocol: in
  407. # cases such as "git+ssh", only use "ssh". (I.e., Only verify against
  408. # the last scheme.)
  409. protocol = origin[0].rsplit('+', 1)[-1]
  410. # Determine if our origin is a secure origin by looking through our
  411. # hardcoded list of secure origins, as well as any additional ones
  412. # configured on this PackageFinder instance.
  413. for secure_origin in (SECURE_ORIGINS + self.secure_origins):
  414. if protocol != secure_origin[0] and secure_origin[0] != "*":
  415. continue
  416. try:
  417. # We need to do this decode dance to ensure that we have a
  418. # unicode object, even on Python 2.x.
  419. addr = ipaddress.ip_address(
  420. origin[1]
  421. if (
  422. isinstance(origin[1], six.text_type) or
  423. origin[1] is None
  424. )
  425. else origin[1].decode("utf8")
  426. )
  427. network = ipaddress.ip_network(
  428. secure_origin[1]
  429. if isinstance(secure_origin[1], six.text_type)
  430. # setting secure_origin[1] to proper Union[bytes, str]
  431. # creates problems in other places
  432. else secure_origin[1].decode("utf8") # type: ignore
  433. )
  434. except ValueError:
  435. # We don't have both a valid address or a valid network, so
  436. # we'll check this origin against hostnames.
  437. if (origin[1] and
  438. origin[1].lower() != secure_origin[1].lower() and
  439. secure_origin[1] != "*"):
  440. continue
  441. else:
  442. # We have a valid address and network, so see if the address
  443. # is contained within the network.
  444. if addr not in network:
  445. continue
  446. # Check to see if the port patches
  447. if (origin[2] != secure_origin[2] and
  448. secure_origin[2] != "*" and
  449. secure_origin[2] is not None):
  450. continue
  451. # If we've gotten here, then this origin matches the current
  452. # secure origin and we should return True
  453. return True
  454. # If we've gotten to this point, then the origin isn't secure and we
  455. # will not accept it as a valid location to search. We will however
  456. # log a warning that we are ignoring it.
  457. logger.warning(
  458. "The repository located at %s is not a trusted or secure host and "
  459. "is being ignored. If this repository is available via HTTPS we "
  460. "recommend you use HTTPS instead, otherwise you may silence "
  461. "this warning and allow it anyway with '--trusted-host %s'.",
  462. parsed.hostname,
  463. parsed.hostname,
  464. )
  465. return False
  466. def _get_index_urls_locations(self, project_name):
  467. # type: (str) -> List[str]
  468. """Returns the locations found via self.index_urls
  469. Checks the url_name on the main (first in the list) index and
  470. use this url_name to produce all locations
  471. """
  472. def mkurl_pypi_url(url):
  473. loc = posixpath.join(
  474. url,
  475. urllib_parse.quote(canonicalize_name(project_name)))
  476. # For maximum compatibility with easy_install, ensure the path
  477. # ends in a trailing slash. Although this isn't in the spec
  478. # (and PyPI can handle it without the slash) some other index
  479. # implementations might break if they relied on easy_install's
  480. # behavior.
  481. if not loc.endswith('/'):
  482. loc = loc + '/'
  483. return loc
  484. return [mkurl_pypi_url(url) for url in self.index_urls]
  485. def find_all_candidates(self, project_name):
  486. # type: (str) -> List[Optional[InstallationCandidate]]
  487. """Find all available InstallationCandidate for project_name
  488. This checks index_urls and find_links.
  489. All versions found are returned as an InstallationCandidate list.
  490. See _link_package_versions for details on which files are accepted
  491. """
  492. index_locations = self._get_index_urls_locations(project_name)
  493. index_file_loc, index_url_loc = self._sort_locations(index_locations)
  494. fl_file_loc, fl_url_loc = self._sort_locations(
  495. self.find_links, expand_dir=True,
  496. )
  497. file_locations = (Link(url) for url in itertools.chain(
  498. index_file_loc, fl_file_loc,
  499. ))
  500. # We trust every url that the user has given us whether it was given
  501. # via --index-url or --find-links.
  502. # We want to filter out any thing which does not have a secure origin.
  503. url_locations = [
  504. link for link in itertools.chain(
  505. (Link(url) for url in index_url_loc),
  506. (Link(url) for url in fl_url_loc),
  507. )
  508. if self._validate_secure_origin(logger, link)
  509. ]
  510. logger.debug('%d location(s) to search for versions of %s:',
  511. len(url_locations), project_name)
  512. for location in url_locations:
  513. logger.debug('* %s', location)
  514. canonical_name = canonicalize_name(project_name)
  515. formats = self.format_control.get_allowed_formats(canonical_name)
  516. search = Search(project_name, canonical_name, formats)
  517. find_links_versions = self._package_versions(
  518. # We trust every directly linked archive in find_links
  519. (Link(url, '-f') for url in self.find_links),
  520. search
  521. )
  522. page_versions = []
  523. for page in self._get_pages(url_locations, project_name):
  524. logger.debug('Analyzing links from page %s', page.url)
  525. with indent_log():
  526. page_versions.extend(
  527. self._package_versions(page.iter_links(), search)
  528. )
  529. file_versions = self._package_versions(file_locations, search)
  530. if file_versions:
  531. file_versions.sort(reverse=True)
  532. logger.debug(
  533. 'Local files found: %s',
  534. ', '.join([
  535. url_to_path(candidate.location.url)
  536. for candidate in file_versions
  537. ])
  538. )
  539. # This is an intentional priority ordering
  540. return file_versions + find_links_versions + page_versions
  541. def find_requirement(self, req, upgrade):
  542. # type: (InstallRequirement, bool) -> Optional[Link]
  543. """Try to find a Link matching req
  544. Expects req, an InstallRequirement and upgrade, a boolean
  545. Returns a Link if found,
  546. Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
  547. """
  548. all_candidates = self.find_all_candidates(req.name)
  549. # Filter out anything which doesn't match our specifier
  550. compatible_versions = set(
  551. req.specifier.filter(
  552. # We turn the version object into a str here because otherwise
  553. # when we're debundled but setuptools isn't, Python will see
  554. # packaging.version.Version and
  555. # pkg_resources._vendor.packaging.version.Version as different
  556. # types. This way we'll use a str as a common data interchange
  557. # format. If we stop using the pkg_resources provided specifier
  558. # and start using our own, we can drop the cast to str().
  559. [str(c.version) for c in all_candidates],
  560. prereleases=(
  561. self.allow_all_prereleases
  562. if self.allow_all_prereleases else None
  563. ),
  564. )
  565. )
  566. applicable_candidates = [
  567. # Again, converting to str to deal with debundling.
  568. c for c in all_candidates if str(c.version) in compatible_versions
  569. ]
  570. if applicable_candidates:
  571. best_candidate = max(applicable_candidates,
  572. key=self._candidate_sort_key)
  573. else:
  574. best_candidate = None
  575. if req.satisfied_by is not None:
  576. installed_version = parse_version(req.satisfied_by.version)
  577. else:
  578. installed_version = None
  579. if installed_version is None and best_candidate is None:
  580. logger.critical(
  581. 'Could not find a version that satisfies the requirement %s '
  582. '(from versions: %s)',
  583. req,
  584. ', '.join(
  585. sorted(
  586. {str(c.version) for c in all_candidates},
  587. key=parse_version,
  588. )
  589. )
  590. )
  591. raise DistributionNotFound(
  592. 'No matching distribution found for %s' % req
  593. )
  594. best_installed = False
  595. if installed_version and (
  596. best_candidate is None or
  597. best_candidate.version <= installed_version):
  598. best_installed = True
  599. if not upgrade and installed_version is not None:
  600. if best_installed:
  601. logger.debug(
  602. 'Existing installed version (%s) is most up-to-date and '
  603. 'satisfies requirement',
  604. installed_version,
  605. )
  606. else:
  607. logger.debug(
  608. 'Existing installed version (%s) satisfies requirement '
  609. '(most up-to-date version is %s)',
  610. installed_version,
  611. best_candidate.version,
  612. )
  613. return None
  614. if best_installed:
  615. # We have an existing version, and its the best version
  616. logger.debug(
  617. 'Installed version (%s) is most up-to-date (past versions: '
  618. '%s)',
  619. installed_version,
  620. ', '.join(sorted(compatible_versions, key=parse_version)) or
  621. "none",
  622. )
  623. raise BestVersionAlreadyInstalled
  624. logger.debug(
  625. 'Using version %s (newest of versions: %s)',
  626. best_candidate.version,
  627. ', '.join(sorted(compatible_versions, key=parse_version))
  628. )
  629. return best_candidate.location
  630. def _get_pages(self, locations, project_name):
  631. # type: (Iterable[Link], str) -> Iterable[HTMLPage]
  632. """
  633. Yields (page, page_url) from the given locations, skipping
  634. locations that have errors.
  635. """
  636. seen = set() # type: Set[Link]
  637. for location in locations:
  638. if location in seen:
  639. continue
  640. seen.add(location)
  641. page = _get_html_page(location, session=self.session)
  642. if page is None:
  643. continue
  644. yield page
  645. _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$')
  646. def _sort_links(self, links):
  647. # type: (Iterable[Link]) -> List[Link]
  648. """
  649. Returns elements of links in order, non-egg links first, egg links
  650. second, while eliminating duplicates
  651. """
  652. eggs, no_eggs = [], []
  653. seen = set() # type: Set[Link]
  654. for link in links:
  655. if link not in seen:
  656. seen.add(link)
  657. if link.egg_fragment:
  658. eggs.append(link)
  659. else:
  660. no_eggs.append(link)
  661. return no_eggs + eggs
  662. def _package_versions(
  663. self,
  664. links, # type: Iterable[Link]
  665. search # type: Search
  666. ):
  667. # type: (...) -> List[Optional[InstallationCandidate]]
  668. result = []
  669. for link in self._sort_links(links):
  670. v = self._link_package_versions(link, search)
  671. if v is not None:
  672. result.append(v)
  673. return result
  674. def _log_skipped_link(self, link, reason):
  675. # type: (Link, str) -> None
  676. if link not in self.logged_links:
  677. logger.debug('Skipping link %s; %s', link, reason)
  678. self.logged_links.add(link)
  679. def _link_package_versions(self, link, search):
  680. # type: (Link, Search) -> Optional[InstallationCandidate]
  681. """Return an InstallationCandidate or None"""
  682. version = None
  683. if link.egg_fragment:
  684. egg_info = link.egg_fragment
  685. ext = link.ext
  686. else:
  687. egg_info, ext = link.splitext()
  688. if not ext:
  689. self._log_skipped_link(link, 'not a file')
  690. return None
  691. if ext not in SUPPORTED_EXTENSIONS:
  692. self._log_skipped_link(
  693. link, 'unsupported archive format: %s' % ext,
  694. )
  695. return None
  696. if "binary" not in search.formats and ext == WHEEL_EXTENSION:
  697. self._log_skipped_link(
  698. link, 'No binaries permitted for %s' % search.supplied,
  699. )
  700. return None
  701. if "macosx10" in link.path and ext == '.zip':
  702. self._log_skipped_link(link, 'macosx10 one')
  703. return None
  704. if ext == WHEEL_EXTENSION:
  705. try:
  706. wheel = Wheel(link.filename)
  707. except InvalidWheelFilename:
  708. self._log_skipped_link(link, 'invalid wheel filename')
  709. return None
  710. if canonicalize_name(wheel.name) != search.canonical:
  711. self._log_skipped_link(
  712. link, 'wrong project name (not %s)' % search.supplied)
  713. return None
  714. if not wheel.supported(self.valid_tags):
  715. self._log_skipped_link(
  716. link, 'it is not compatible with this Python')
  717. return None
  718. version = wheel.version
  719. # This should be up by the search.ok_binary check, but see issue 2700.
  720. if "source" not in search.formats and ext != WHEEL_EXTENSION:
  721. self._log_skipped_link(
  722. link, 'No sources permitted for %s' % search.supplied,
  723. )
  724. return None
  725. if not version:
  726. version = _egg_info_matches(egg_info, search.canonical)
  727. if not version:
  728. self._log_skipped_link(
  729. link, 'Missing project version for %s' % search.supplied)
  730. return None
  731. match = self._py_version_re.search(version)
  732. if match:
  733. version = version[:match.start()]
  734. py_version = match.group(1)
  735. if py_version != sys.version[:3]:
  736. self._log_skipped_link(
  737. link, 'Python version is incorrect')
  738. return None
  739. try:
  740. support_this_python = check_requires_python(link.requires_python)
  741. except specifiers.InvalidSpecifier:
  742. logger.debug("Package %s has an invalid Requires-Python entry: %s",
  743. link.filename, link.requires_python)
  744. support_this_python = True
  745. if not support_this_python:
  746. logger.debug("The package %s is incompatible with the python "
  747. "version in use. Acceptable python versions are: %s",
  748. link, link.requires_python)
  749. return None
  750. logger.debug('Found link %s, version: %s', link, version)
  751. return InstallationCandidate(search.supplied, version, link)
  752. def _find_name_version_sep(egg_info, canonical_name):
  753. # type: (str, str) -> int
  754. """Find the separator's index based on the package's canonical name.
  755. `egg_info` must be an egg info string for the given package, and
  756. `canonical_name` must be the package's canonical name.
  757. This function is needed since the canonicalized name does not necessarily
  758. have the same length as the egg info's name part. An example::
  759. >>> egg_info = 'foo__bar-1.0'
  760. >>> canonical_name = 'foo-bar'
  761. >>> _find_name_version_sep(egg_info, canonical_name)
  762. 8
  763. """
  764. # Project name and version must be separated by one single dash. Find all
  765. # occurrences of dashes; if the string in front of it matches the canonical
  766. # name, this is the one separating the name and version parts.
  767. for i, c in enumerate(egg_info):
  768. if c != "-":
  769. continue
  770. if canonicalize_name(egg_info[:i]) == canonical_name:
  771. return i
  772. raise ValueError("{} does not match {}".format(egg_info, canonical_name))
  773. def _egg_info_matches(egg_info, canonical_name):
  774. # type: (str, str) -> Optional[str]
  775. """Pull the version part out of a string.
  776. :param egg_info: The string to parse. E.g. foo-2.1
  777. :param canonical_name: The canonicalized name of the package this
  778. belongs to.
  779. """
  780. try:
  781. version_start = _find_name_version_sep(egg_info, canonical_name) + 1
  782. except ValueError:
  783. return None
  784. version = egg_info[version_start:]
  785. if not version:
  786. return None
  787. return version
  788. def _determine_base_url(document, page_url):
  789. """Determine the HTML document's base URL.
  790. This looks for a ``<base>`` tag in the HTML document. If present, its href
  791. attribute denotes the base URL of anchor tags in the document. If there is
  792. no such tag (or if it does not have a valid href attribute), the HTML
  793. file's URL is used as the base URL.
  794. :param document: An HTML document representation. The current
  795. implementation expects the result of ``html5lib.parse()``.
  796. :param page_url: The URL of the HTML document.
  797. """
  798. for base in document.findall(".//base"):
  799. href = base.get("href")
  800. if href is not None:
  801. return href
  802. return page_url
  803. def _get_encoding_from_headers(headers):
  804. """Determine if we have any encoding information in our headers.
  805. """
  806. if headers and "Content-Type" in headers:
  807. content_type, params = cgi.parse_header(headers["Content-Type"])
  808. if "charset" in params:
  809. return params['charset']
  810. return None
  811. _CLEAN_LINK_RE = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
  812. def _clean_link(url):
  813. # type: (str) -> str
  814. """Makes sure a link is fully encoded. That is, if a ' ' shows up in
  815. the link, it will be rewritten to %20 (while not over-quoting
  816. % or other characters)."""
  817. return _CLEAN_LINK_RE.sub(lambda match: '%%%2x' % ord(match.group(0)), url)
  818. class HTMLPage(object):
  819. """Represents one page, along with its URL"""
  820. def __init__(self, content, url, headers=None):
  821. # type: (bytes, str, MutableMapping[str, str]) -> None
  822. self.content = content
  823. self.url = url
  824. self.headers = headers
  825. def __str__(self):
  826. return redact_password_from_url(self.url)
  827. def iter_links(self):
  828. # type: () -> Iterable[Link]
  829. """Yields all links in the page"""
  830. document = html5lib.parse(
  831. self.content,
  832. transport_encoding=_get_encoding_from_headers(self.headers),
  833. namespaceHTMLElements=False,
  834. )
  835. base_url = _determine_base_url(document, self.url)
  836. for anchor in document.findall(".//a"):
  837. if anchor.get("href"):
  838. href = anchor.get("href")
  839. url = _clean_link(urllib_parse.urljoin(base_url, href))
  840. pyrequire = anchor.get('data-requires-python')
  841. pyrequire = unescape(pyrequire) if pyrequire else None
  842. yield Link(url, self.url, requires_python=pyrequire)
  843. Search = namedtuple('Search', 'supplied canonical formats')
  844. """Capture key aspects of a search.
  845. :attribute supplied: The user supplied package.
  846. :attribute canonical: The canonical package name.
  847. :attribute formats: The formats allowed for this package. Should be a set
  848. with 'binary' or 'source' or both in it.
  849. """