Development of an internal social media platform with personalised dashboards for students
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 34KB

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