index.py 40 KB

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