PageRenderTime 60ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/pip/index.py

https://github.com/ptthiem/pip
Python | 993 lines | 837 code | 61 blank | 95 comment | 123 complexity | a57ecc099c085dc73159b8c10f5d6b24 MD5 | raw file
  1. """Routines related to PyPI, indexes"""
  2. import sys
  3. import os
  4. import re
  5. import mimetypes
  6. import posixpath
  7. import pkg_resources
  8. from pip.log import logger
  9. from pip.util import Inf, normalize_name, splitext, is_prerelease
  10. from pip.exceptions import (DistributionNotFound, BestVersionAlreadyInstalled,
  11. InstallationError, InvalidWheelFilename, UnsupportedWheel)
  12. from pip.backwardcompat import urlparse, url2pathname
  13. from pip.download import PipSession, url_to_path, path_to_url
  14. from pip.wheel import Wheel, wheel_ext, wheel_setuptools_support
  15. from pip.pep425tags import supported_tags, supported_tags_noarch, get_platform
  16. from pip._vendor import html5lib, requests
  17. from pip._vendor.requests.exceptions import SSLError
  18. __all__ = ['PackageFinder']
  19. DEFAULT_MIRROR_HOSTNAME = "last.pypi.python.org"
  20. INSECURE_SCHEMES = {
  21. "http": ["https"],
  22. }
  23. class PackageFinder(object):
  24. """This finds packages.
  25. This is meant to match easy_install's technique for looking for
  26. packages, by reading pages and looking for appropriate links
  27. """
  28. def __init__(self, find_links, index_urls,
  29. use_wheel=True, allow_external=[], allow_unverified=[],
  30. allow_all_external=False, allow_all_prereleases=False,
  31. process_dependency_links=False, session=None):
  32. self.find_links = find_links
  33. self.index_urls = index_urls
  34. self.dependency_links = []
  35. self.cache = PageCache()
  36. # These are boring links that have already been logged somehow:
  37. self.logged_links = set()
  38. self.use_wheel = use_wheel
  39. # Do we allow (safe and verifiable) externally hosted files?
  40. self.allow_external = set(normalize_name(n) for n in allow_external)
  41. # Which names are allowed to install insecure and unverifiable files?
  42. self.allow_unverified = set(
  43. normalize_name(n) for n in allow_unverified
  44. )
  45. # Do we allow all (safe and verifiable) externally hosted files?
  46. self.allow_all_external = allow_all_external
  47. # Stores if we ignored any external links so that we can instruct
  48. # end users how to install them if no distributions are available
  49. self.need_warn_external = False
  50. # Stores if we ignored any unsafe links so that we can instruct
  51. # end users how to install them if no distributions are available
  52. self.need_warn_unverified = False
  53. # Do we want to allow _all_ pre-releases?
  54. self.allow_all_prereleases = allow_all_prereleases
  55. # Do we process dependency links?
  56. self.process_dependency_links = process_dependency_links
  57. self._have_warned_dependency_links = False
  58. # The Session we'll use to make requests
  59. self.session = session or PipSession()
  60. @property
  61. def use_wheel(self):
  62. return self._use_wheel
  63. @use_wheel.setter
  64. def use_wheel(self, value):
  65. self._use_wheel = value
  66. if self._use_wheel and not wheel_setuptools_support():
  67. raise InstallationError("pip's wheel support requires setuptools >= 0.8 for dist-info support.")
  68. def add_dependency_links(self, links):
  69. ## FIXME: this shouldn't be global list this, it should only
  70. ## apply to requirements of the package that specifies the
  71. ## dependency_links value
  72. ## FIXME: also, we should track comes_from (i.e., use Link)
  73. if self.process_dependency_links:
  74. if not self._have_warned_dependency_links:
  75. logger.deprecated(
  76. "1.6",
  77. "Dependency Links processing has been deprecated with an "
  78. "accelerated time schedule and will be removed in pip 1.6",
  79. )
  80. self._have_warned_dependency_links = True
  81. self.dependency_links.extend(links)
  82. def _sort_locations(self, locations):
  83. """
  84. Sort locations into "files" (archives) and "urls", and return
  85. a pair of lists (files,urls)
  86. """
  87. files = []
  88. urls = []
  89. # puts the url for the given file path into the appropriate list
  90. def sort_path(path):
  91. url = path_to_url(path)
  92. if mimetypes.guess_type(url, strict=False)[0] == 'text/html':
  93. urls.append(url)
  94. else:
  95. files.append(url)
  96. for url in locations:
  97. is_local_path = os.path.exists(url)
  98. is_file_url = url.startswith('file:')
  99. is_find_link = url in self.find_links
  100. if is_local_path or is_file_url:
  101. if is_local_path:
  102. path = url
  103. else:
  104. path = url_to_path(url)
  105. if is_find_link and os.path.isdir(path):
  106. path = os.path.realpath(path)
  107. for item in os.listdir(path):
  108. sort_path(os.path.join(path, item))
  109. elif is_file_url and os.path.isdir(path):
  110. urls.append(url)
  111. elif os.path.isfile(path):
  112. sort_path(path)
  113. else:
  114. urls.append(url)
  115. return files, urls
  116. def _link_sort_key(self, link_tuple):
  117. """
  118. Function used to generate link sort key for link tuples.
  119. The greater the return value, the more preferred it is.
  120. If not finding wheels, then sorted by version only.
  121. If finding wheels, then the sort order is by version, then:
  122. 1. existing installs
  123. 2. wheels ordered via Wheel.support_index_min()
  124. 3. source archives
  125. Note: it was considered to embed this logic into the Link
  126. comparison operators, but then different sdist links
  127. with the same version, would have to be considered equal
  128. """
  129. parsed_version, link, _ = link_tuple
  130. if self.use_wheel:
  131. support_num = len(supported_tags)
  132. if link == INSTALLED_VERSION:
  133. pri = 1
  134. elif link.ext == wheel_ext:
  135. wheel = Wheel(link.filename) # can raise InvalidWheelFilename
  136. if not wheel.supported():
  137. raise UnsupportedWheel("%s is not a supported wheel for this platform. It can't be sorted." % wheel.filename)
  138. pri = -(wheel.support_index_min())
  139. else: # sdist
  140. pri = -(support_num)
  141. return (parsed_version, pri)
  142. else:
  143. return parsed_version
  144. def _sort_versions(self, applicable_versions):
  145. """
  146. Bring the latest version (and wheels) to the front, but maintain the existing ordering as secondary.
  147. See the docstring for `_link_sort_key` for details.
  148. This function is isolated for easier unit testing.
  149. """
  150. return sorted(applicable_versions, key=self._link_sort_key, reverse=True)
  151. def find_requirement(self, req, upgrade):
  152. def mkurl_pypi_url(url):
  153. loc = posixpath.join(url, url_name)
  154. # For maximum compatibility with easy_install, ensure the path
  155. # ends in a trailing slash. Although this isn't in the spec
  156. # (and PyPI can handle it without the slash) some other index
  157. # implementations might break if they relied on easy_install's behavior.
  158. if not loc.endswith('/'):
  159. loc = loc + '/'
  160. return loc
  161. url_name = req.url_name
  162. # Only check main index if index URL is given:
  163. main_index_url = None
  164. if self.index_urls:
  165. # Check that we have the url_name correctly spelled:
  166. main_index_url = Link(mkurl_pypi_url(self.index_urls[0]), trusted=True)
  167. # This will also cache the page, so it's okay that we get it again later:
  168. page = self._get_page(main_index_url, req)
  169. if page is None:
  170. url_name = self._find_url_name(Link(self.index_urls[0], trusted=True), url_name, req) or req.url_name
  171. if url_name is not None:
  172. locations = [
  173. mkurl_pypi_url(url)
  174. for url in self.index_urls] + self.find_links
  175. else:
  176. locations = list(self.find_links)
  177. for version in req.absolute_versions:
  178. if url_name is not None and main_index_url is not None:
  179. locations = [
  180. posixpath.join(main_index_url.url, version)] + locations
  181. file_locations, url_locations = self._sort_locations(locations)
  182. _flocations, _ulocations = self._sort_locations(self.dependency_links)
  183. file_locations.extend(_flocations)
  184. # We trust every url that the user has given us whether it was given
  185. # via --index-url or --find-links
  186. locations = [Link(url, trusted=True) for url in url_locations]
  187. # We explicitly do not trust links that came from dependency_links
  188. locations.extend([Link(url) for url in _ulocations])
  189. logger.debug('URLs to search for versions for %s:' % req)
  190. for location in locations:
  191. logger.debug('* %s' % location)
  192. # Determine if this url used a secure transport mechanism
  193. parsed = urlparse.urlparse(str(location))
  194. if parsed.scheme in INSECURE_SCHEMES:
  195. secure_schemes = INSECURE_SCHEMES[parsed.scheme]
  196. if len(secure_schemes) == 1:
  197. ctx = (location, parsed.scheme, secure_schemes[0],
  198. parsed.netloc)
  199. logger.warn("%s uses an insecure transport scheme (%s). "
  200. "Consider using %s if %s has it available" %
  201. ctx)
  202. elif len(secure_schemes) > 1:
  203. ctx = (location, parsed.scheme, ", ".join(secure_schemes),
  204. parsed.netloc)
  205. logger.warn("%s uses an insecure transport scheme (%s). "
  206. "Consider using one of %s if %s has any of "
  207. "them available" % ctx)
  208. else:
  209. ctx = (location, parsed.scheme)
  210. logger.warn("%s uses an insecure transport scheme (%s)." %
  211. ctx)
  212. found_versions = []
  213. found_versions.extend(
  214. self._package_versions(
  215. # We trust every directly linked archive in find_links
  216. [Link(url, '-f', trusted=True) for url in self.find_links], req.name.lower()))
  217. page_versions = []
  218. for page in self._get_pages(locations, req):
  219. logger.debug('Analyzing links from page %s' % page.url)
  220. logger.indent += 2
  221. try:
  222. page_versions.extend(self._package_versions(page.links, req.name.lower()))
  223. finally:
  224. logger.indent -= 2
  225. dependency_versions = list(self._package_versions(
  226. [Link(url) for url in self.dependency_links], req.name.lower()))
  227. if dependency_versions:
  228. logger.info('dependency_links found: %s' % ', '.join([link.url for parsed, link, version in dependency_versions]))
  229. file_versions = list(self._package_versions(
  230. [Link(url) for url in file_locations], req.name.lower()))
  231. if not found_versions and not page_versions and not dependency_versions and not file_versions:
  232. logger.fatal('Could not find any downloads that satisfy the requirement %s' % req)
  233. if self.need_warn_external:
  234. logger.warn("Some externally hosted files were ignored (use "
  235. "--allow-external %s to allow)." % req.name)
  236. if self.need_warn_unverified:
  237. logger.warn("Some insecure and unverifiable files were ignored"
  238. " (use --allow-unverified %s to allow)." %
  239. req.name)
  240. raise DistributionNotFound('No distributions at all found for %s' % req)
  241. installed_version = []
  242. if req.satisfied_by is not None:
  243. installed_version = [(req.satisfied_by.parsed_version, INSTALLED_VERSION, req.satisfied_by.version)]
  244. if file_versions:
  245. file_versions.sort(reverse=True)
  246. logger.info('Local files found: %s' % ', '.join([url_to_path(link.url) for parsed, link, version in file_versions]))
  247. #this is an intentional priority ordering
  248. all_versions = installed_version + file_versions + found_versions + page_versions + dependency_versions
  249. applicable_versions = []
  250. for (parsed_version, link, version) in all_versions:
  251. if version not in req.req:
  252. logger.info("Ignoring link %s, version %s doesn't match %s"
  253. % (link, version, ','.join([''.join(s) for s in req.req.specs])))
  254. continue
  255. elif is_prerelease(version) and not (self.allow_all_prereleases or req.prereleases):
  256. # If this version isn't the already installed one, then
  257. # ignore it if it's a pre-release.
  258. if link is not INSTALLED_VERSION:
  259. logger.info("Ignoring link %s, version %s is a pre-release (use --pre to allow)." % (link, version))
  260. continue
  261. applicable_versions.append((parsed_version, link, version))
  262. applicable_versions = self._sort_versions(applicable_versions)
  263. existing_applicable = bool([link for parsed_version, link, version in applicable_versions if link is INSTALLED_VERSION])
  264. if not upgrade and existing_applicable:
  265. if applicable_versions[0][1] is INSTALLED_VERSION:
  266. logger.info('Existing installed version (%s) is most up-to-date and satisfies requirement'
  267. % req.satisfied_by.version)
  268. else:
  269. logger.info('Existing installed version (%s) satisfies requirement (most up-to-date version is %s)'
  270. % (req.satisfied_by.version, applicable_versions[0][2]))
  271. return None
  272. if not applicable_versions:
  273. logger.fatal('Could not find a version that satisfies the requirement %s (from versions: %s)'
  274. % (req, ', '.join([version for parsed_version, link, version in all_versions])))
  275. if self.need_warn_external:
  276. logger.warn("Some externally hosted files were ignored (use "
  277. "--allow-external to allow).")
  278. if self.need_warn_unverified:
  279. logger.warn("Some insecure and unverifiable files were ignored"
  280. " (use --allow-unverified %s to allow)." %
  281. req.name)
  282. raise DistributionNotFound('No distributions matching the version for %s' % req)
  283. if applicable_versions[0][1] is INSTALLED_VERSION:
  284. # We have an existing version, and its the best version
  285. logger.info('Installed version (%s) is most up-to-date (past versions: %s)'
  286. % (req.satisfied_by.version, ', '.join([version for parsed_version, link, version in applicable_versions[1:]]) or 'none'))
  287. raise BestVersionAlreadyInstalled
  288. if len(applicable_versions) > 1:
  289. logger.info('Using version %s (newest of versions: %s)' %
  290. (applicable_versions[0][2], ', '.join([version for parsed_version, link, version in applicable_versions])))
  291. selected_version = applicable_versions[0][1]
  292. if (selected_version.internal is not None
  293. and not selected_version.internal):
  294. logger.warn("%s an externally hosted file and may be "
  295. "unreliable" % req.name)
  296. if (selected_version.verifiable is not None
  297. and not selected_version.verifiable):
  298. logger.warn("%s is potentially insecure and "
  299. "unverifiable." % req.name)
  300. if selected_version._deprecated_regex:
  301. logger.deprecated(
  302. "1.7",
  303. "%s discovered using a deprecated method of parsing, "
  304. "in the future it will no longer be discovered" % req.name
  305. )
  306. return selected_version
  307. def _find_url_name(self, index_url, url_name, req):
  308. """Finds the true URL name of a package, when the given name isn't quite correct.
  309. This is usually used to implement case-insensitivity."""
  310. if not index_url.url.endswith('/'):
  311. # Vaguely part of the PyPI API... weird but true.
  312. ## FIXME: bad to modify this?
  313. index_url.url += '/'
  314. page = self._get_page(index_url, req)
  315. if page is None:
  316. logger.fatal('Cannot fetch index base URL %s' % index_url)
  317. return
  318. norm_name = normalize_name(req.url_name)
  319. for link in page.links:
  320. base = posixpath.basename(link.path.rstrip('/'))
  321. if norm_name == normalize_name(base):
  322. logger.notify('Real name of requirement %s is %s' % (url_name, base))
  323. return base
  324. return None
  325. def _get_pages(self, locations, req):
  326. """
  327. Yields (page, page_url) from the given locations, skipping
  328. locations that have errors, and adding download/homepage links
  329. """
  330. all_locations = list(locations)
  331. seen = set()
  332. while all_locations:
  333. location = all_locations.pop(0)
  334. if location in seen:
  335. continue
  336. seen.add(location)
  337. page = self._get_page(location, req)
  338. if page is None:
  339. continue
  340. yield page
  341. for link in page.rel_links():
  342. normalized = normalize_name(req.name).lower()
  343. if (not normalized in self.allow_external
  344. and not self.allow_all_external):
  345. self.need_warn_external = True
  346. logger.debug("Not searching %s for files because external "
  347. "urls are disallowed." % link)
  348. continue
  349. if (link.trusted is not None
  350. and not link.trusted
  351. and not normalized in self.allow_unverified):
  352. logger.debug("Not searching %s for urls, it is an "
  353. "untrusted link and cannot produce safe or "
  354. "verifiable files." % link)
  355. self.need_warn_unverified = True
  356. continue
  357. all_locations.append(link)
  358. _egg_fragment_re = re.compile(r'#egg=([^&]*)')
  359. _egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.-]+)', re.I)
  360. _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$')
  361. def _sort_links(self, links):
  362. "Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates"
  363. eggs, no_eggs = [], []
  364. seen = set()
  365. for link in links:
  366. if link not in seen:
  367. seen.add(link)
  368. if link.egg_fragment:
  369. eggs.append(link)
  370. else:
  371. no_eggs.append(link)
  372. return no_eggs + eggs
  373. def _package_versions(self, links, search_name):
  374. for link in self._sort_links(links):
  375. for v in self._link_package_versions(link, search_name):
  376. yield v
  377. def _known_extensions(self):
  378. extensions = ('.tar.gz', '.tar.bz2', '.tar', '.tgz', '.zip')
  379. if self.use_wheel:
  380. return extensions + (wheel_ext,)
  381. return extensions
  382. def _link_package_versions(self, link, search_name):
  383. """
  384. Return an iterable of triples (pkg_resources_version_key,
  385. link, python_version) that can be extracted from the given
  386. link.
  387. Meant to be overridden by subclasses, not called by clients.
  388. """
  389. platform = get_platform()
  390. version = None
  391. if link.egg_fragment:
  392. egg_info = link.egg_fragment
  393. else:
  394. egg_info, ext = link.splitext()
  395. if not ext:
  396. if link not in self.logged_links:
  397. logger.debug('Skipping link %s; not a file' % link)
  398. self.logged_links.add(link)
  399. return []
  400. if egg_info.endswith('.tar'):
  401. # Special double-extension case:
  402. egg_info = egg_info[:-4]
  403. ext = '.tar' + ext
  404. if ext not in self._known_extensions():
  405. if link not in self.logged_links:
  406. logger.debug('Skipping link %s; unknown archive format: %s' % (link, ext))
  407. self.logged_links.add(link)
  408. return []
  409. if "macosx10" in link.path and ext == '.zip':
  410. if link not in self.logged_links:
  411. logger.debug('Skipping link %s; macosx10 one' % (link))
  412. self.logged_links.add(link)
  413. return []
  414. if ext == wheel_ext:
  415. try:
  416. wheel = Wheel(link.filename)
  417. except InvalidWheelFilename:
  418. logger.debug('Skipping %s because the wheel filename is invalid' % link)
  419. return []
  420. if wheel.name.lower() != search_name.lower():
  421. logger.debug('Skipping link %s; wrong project name (not %s)' % (link, search_name))
  422. return []
  423. if not wheel.supported():
  424. logger.debug('Skipping %s because it is not compatible with this Python' % link)
  425. return []
  426. # This is a dirty hack to prevent installing Binary Wheels from
  427. # PyPI unless it is a Windows or Mac Binary Wheel. This is
  428. # paired with a change to PyPI disabling uploads for the
  429. # same. Once we have a mechanism for enabling support for binary
  430. # wheels on linux that deals with the inherent problems of
  431. # binary distribution this can be removed.
  432. comes_from = getattr(link, "comes_from", None)
  433. if ((
  434. not platform.startswith('win')
  435. and not platform.startswith('macosx')
  436. )
  437. and comes_from is not None
  438. and urlparse.urlparse(comes_from.url).netloc.endswith(
  439. "pypi.python.org")):
  440. if not wheel.supported(tags=supported_tags_noarch):
  441. logger.debug(
  442. "Skipping %s because it is a pypi-hosted binary "
  443. "Wheel on an unsupported platform" % link
  444. )
  445. return []
  446. version = wheel.version
  447. if not version:
  448. version = self._egg_info_matches(egg_info, search_name, link)
  449. if version is None:
  450. logger.debug('Skipping link %s; wrong project name (not %s)' % (link, search_name))
  451. return []
  452. if (link.internal is not None
  453. and not link.internal
  454. and not normalize_name(search_name).lower() in self.allow_external
  455. and not self.allow_all_external):
  456. # We have a link that we are sure is external, so we should skip
  457. # it unless we are allowing externals
  458. logger.debug("Skipping %s because it is externally hosted." % link)
  459. self.need_warn_external = True
  460. return []
  461. if (link.verifiable is not None
  462. and not link.verifiable
  463. and not (normalize_name(search_name).lower()
  464. in self.allow_unverified)):
  465. # We have a link that we are sure we cannot verify it's integrity,
  466. # so we should skip it unless we are allowing unsafe installs
  467. # for this requirement.
  468. logger.debug("Skipping %s because it is an insecure and "
  469. "unverifiable file." % link)
  470. self.need_warn_unverified = True
  471. return []
  472. match = self._py_version_re.search(version)
  473. if match:
  474. version = version[:match.start()]
  475. py_version = match.group(1)
  476. if py_version != sys.version[:3]:
  477. logger.debug('Skipping %s because Python version is incorrect' % link)
  478. return []
  479. logger.debug('Found link %s, version: %s' % (link, version))
  480. return [(pkg_resources.parse_version(version),
  481. link,
  482. version)]
  483. def _egg_info_matches(self, egg_info, search_name, link):
  484. match = self._egg_info_re.search(egg_info)
  485. if not match:
  486. logger.debug('Could not parse version from link: %s' % link)
  487. return None
  488. name = match.group(0).lower()
  489. # To match the "safe" name that pkg_resources creates:
  490. name = name.replace('_', '-')
  491. # project name and version must be separated by a dash
  492. look_for = search_name.lower() + "-"
  493. if name.startswith(look_for):
  494. return match.group(0)[len(look_for):]
  495. else:
  496. return None
  497. def _get_page(self, link, req):
  498. return HTMLPage.get_page(link, req,
  499. cache=self.cache,
  500. session=self.session,
  501. )
  502. class PageCache(object):
  503. """Cache of HTML pages"""
  504. failure_limit = 3
  505. def __init__(self):
  506. self._failures = {}
  507. self._pages = {}
  508. self._archives = {}
  509. def too_many_failures(self, url):
  510. return self._failures.get(url, 0) >= self.failure_limit
  511. def get_page(self, url):
  512. return self._pages.get(url)
  513. def is_archive(self, url):
  514. return self._archives.get(url, False)
  515. def set_is_archive(self, url, value=True):
  516. self._archives[url] = value
  517. def add_page_failure(self, url, level):
  518. self._failures[url] = self._failures.get(url, 0)+level
  519. def add_page(self, urls, page):
  520. for url in urls:
  521. self._pages[url] = page
  522. class HTMLPage(object):
  523. """Represents one page, along with its URL"""
  524. ## FIXME: these regexes are horrible hacks:
  525. _homepage_re = re.compile(r'<th>\s*home\s*page', re.I)
  526. _download_re = re.compile(r'<th>\s*download\s+url', re.I)
  527. _href_re = re.compile('href=(?:"([^"]*)"|\'([^\']*)\'|([^>\\s\\n]*))', re.I|re.S)
  528. def __init__(self, content, url, headers=None, trusted=None):
  529. self.content = content
  530. self.parsed = html5lib.parse(self.content, namespaceHTMLElements=False)
  531. self.url = url
  532. self.headers = headers
  533. self.trusted = trusted
  534. def __str__(self):
  535. return self.url
  536. @classmethod
  537. def get_page(cls, link, req, cache=None, skip_archives=True, session=None):
  538. if session is None:
  539. session = PipSession()
  540. url = link.url
  541. url = url.split('#', 1)[0]
  542. if cache.too_many_failures(url):
  543. return None
  544. # Check for VCS schemes that do not support lookup as web pages.
  545. from pip.vcs import VcsSupport
  546. for scheme in VcsSupport.schemes:
  547. if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
  548. logger.debug('Cannot look at %(scheme)s URL %(link)s' % locals())
  549. return None
  550. if cache is not None:
  551. inst = cache.get_page(url)
  552. if inst is not None:
  553. return inst
  554. try:
  555. if skip_archives:
  556. if cache is not None:
  557. if cache.is_archive(url):
  558. return None
  559. filename = link.filename
  560. for bad_ext in ['.tar', '.tar.gz', '.tar.bz2', '.tgz', '.zip']:
  561. if filename.endswith(bad_ext):
  562. content_type = cls._get_content_type(url,
  563. session=session,
  564. )
  565. if content_type.lower().startswith('text/html'):
  566. break
  567. else:
  568. logger.debug('Skipping page %s because of Content-Type: %s' % (link, content_type))
  569. if cache is not None:
  570. cache.set_is_archive(url)
  571. return None
  572. logger.debug('Getting page %s' % url)
  573. # Tack index.html onto file:// URLs that point to directories
  574. (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
  575. if scheme == 'file' and os.path.isdir(url2pathname(path)):
  576. # add trailing slash if not present so urljoin doesn't trim final segment
  577. if not url.endswith('/'):
  578. url += '/'
  579. url = urlparse.urljoin(url, 'index.html')
  580. logger.debug(' file: URL is directory, getting %s' % url)
  581. resp = session.get(url)
  582. resp.raise_for_status()
  583. # The check for archives above only works if the url ends with
  584. # something that looks like an archive. However that is not a
  585. # requirement. For instance http://sourceforge.net/projects/docutils/files/docutils/0.8.1/docutils-0.8.1.tar.gz/download
  586. # redirects to http://superb-dca3.dl.sourceforge.net/project/docutils/docutils/0.8.1/docutils-0.8.1.tar.gz
  587. # Unless we issue a HEAD request on every url we cannot know
  588. # ahead of time for sure if something is HTML or not. However we
  589. # can check after we've downloaded it.
  590. content_type = resp.headers.get('Content-Type', 'unknown')
  591. if not content_type.lower().startswith("text/html"):
  592. logger.debug('Skipping page %s because of Content-Type: %s' %
  593. (link, content_type))
  594. if cache is not None:
  595. cache.set_is_archive(url)
  596. return None
  597. inst = cls(resp.text, resp.url, resp.headers, trusted=link.trusted)
  598. except requests.HTTPError as exc:
  599. level = 2 if exc.response.status_code == 404 else 1
  600. cls._handle_fail(req, link, exc, url, cache=cache, level=level)
  601. except requests.Timeout:
  602. cls._handle_fail(req, link, "timed out", url, cache=cache)
  603. except SSLError as exc:
  604. reason = ("There was a problem confirming the ssl certificate: "
  605. "%s" % exc)
  606. cls._handle_fail(req, link, reason, url,
  607. cache=cache,
  608. level=2,
  609. meth=logger.notify,
  610. )
  611. else:
  612. if cache is not None:
  613. cache.add_page([url, resp.url], inst)
  614. return inst
  615. @staticmethod
  616. def _handle_fail(req, link, reason, url, cache=None, level=1, meth=None):
  617. if meth is None:
  618. meth = logger.info
  619. meth("Could not fetch URL %s: %s", link, reason)
  620. meth("Will skip URL %s when looking for download links for %s" %
  621. (link.url, req))
  622. if cache is not None:
  623. cache.add_page_failure(url, level)
  624. @staticmethod
  625. def _get_content_type(url, session=None):
  626. """Get the Content-Type of the given url, using a HEAD request"""
  627. if session is None:
  628. session = PipSession()
  629. scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
  630. if not scheme in ('http', 'https', 'ftp', 'ftps'):
  631. ## FIXME: some warning or something?
  632. ## assertion error?
  633. return ''
  634. resp = session.head(url, allow_redirects=True)
  635. resp.raise_for_status()
  636. return resp.headers.get("Content-Type", "")
  637. @property
  638. def api_version(self):
  639. if not hasattr(self, "_api_version"):
  640. _api_version = None
  641. metas = [x for x in self.parsed.findall(".//meta")
  642. if x.get("name", "").lower() == "api-version"]
  643. if metas:
  644. try:
  645. _api_version = int(metas[0].get("value", None))
  646. except (TypeError, ValueError):
  647. _api_version = None
  648. self._api_version = _api_version
  649. return self._api_version
  650. @property
  651. def base_url(self):
  652. if not hasattr(self, "_base_url"):
  653. base = self.parsed.find(".//base")
  654. if base is not None and base.get("href"):
  655. self._base_url = base.get("href")
  656. else:
  657. self._base_url = self.url
  658. return self._base_url
  659. @property
  660. def links(self):
  661. """Yields all links in the page"""
  662. for anchor in self.parsed.findall(".//a"):
  663. if anchor.get("href"):
  664. href = anchor.get("href")
  665. url = self.clean_link(urlparse.urljoin(self.base_url, href))
  666. # Determine if this link is internal. If that distinction
  667. # doesn't make sense in this context, then we don't make
  668. # any distinction.
  669. internal = None
  670. if self.api_version and self.api_version >= 2:
  671. # Only api_versions >= 2 have a distinction between
  672. # external and internal links
  673. internal = bool(anchor.get("rel")
  674. and "internal" in anchor.get("rel").split())
  675. yield Link(url, self, internal=internal)
  676. def rel_links(self):
  677. for url in self.explicit_rel_links():
  678. yield url
  679. for url in self.scraped_rel_links():
  680. yield url
  681. def explicit_rel_links(self, rels=('homepage', 'download')):
  682. """Yields all links with the given relations"""
  683. rels = set(rels)
  684. for anchor in self.parsed.findall(".//a"):
  685. if anchor.get("rel") and anchor.get("href"):
  686. found_rels = set(anchor.get("rel").split())
  687. # Determine the intersection between what rels were found and
  688. # what rels were being looked for
  689. if found_rels & rels:
  690. href = anchor.get("href")
  691. url = self.clean_link(urlparse.urljoin(self.base_url, href))
  692. yield Link(url, self, trusted=False)
  693. def scraped_rel_links(self):
  694. # Can we get rid of this horrible horrible method?
  695. for regex in (self._homepage_re, self._download_re):
  696. match = regex.search(self.content)
  697. if not match:
  698. continue
  699. href_match = self._href_re.search(self.content, pos=match.end())
  700. if not href_match:
  701. continue
  702. url = href_match.group(1) or href_match.group(2) or href_match.group(3)
  703. if not url:
  704. continue
  705. url = self.clean_link(urlparse.urljoin(self.base_url, url))
  706. yield Link(url, self, trusted=False, _deprecated_regex=True)
  707. _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
  708. def clean_link(self, url):
  709. """Makes sure a link is fully encoded. That is, if a ' ' shows up in
  710. the link, it will be rewritten to %20 (while not over-quoting
  711. % or other characters)."""
  712. return self._clean_re.sub(
  713. lambda match: '%%%2x' % ord(match.group(0)), url)
  714. class Link(object):
  715. def __init__(self, url, comes_from=None, internal=None, trusted=None,
  716. _deprecated_regex=False):
  717. self.url = url
  718. self.comes_from = comes_from
  719. self.internal = internal
  720. self.trusted = trusted
  721. self._deprecated_regex = _deprecated_regex
  722. def __str__(self):
  723. if self.comes_from:
  724. return '%s (from %s)' % (self.url, self.comes_from)
  725. else:
  726. return str(self.url)
  727. def __repr__(self):
  728. return '<Link %s>' % self
  729. def __eq__(self, other):
  730. return self.url == other.url
  731. def __ne__(self, other):
  732. return self.url != other.url
  733. def __lt__(self, other):
  734. return self.url < other.url
  735. def __le__(self, other):
  736. return self.url <= other.url
  737. def __gt__(self, other):
  738. return self.url > other.url
  739. def __ge__(self, other):
  740. return self.url >= other.url
  741. def __hash__(self):
  742. return hash(self.url)
  743. @property
  744. def filename(self):
  745. _, netloc, path, _, _ = urlparse.urlsplit(self.url)
  746. name = posixpath.basename(path.rstrip('/')) or netloc
  747. assert name, ('URL %r produced no filename' % self.url)
  748. return name
  749. @property
  750. def scheme(self):
  751. return urlparse.urlsplit(self.url)[0]
  752. @property
  753. def path(self):
  754. return urlparse.urlsplit(self.url)[2]
  755. def splitext(self):
  756. return splitext(posixpath.basename(self.path.rstrip('/')))
  757. @property
  758. def ext(self):
  759. return self.splitext()[1]
  760. @property
  761. def url_without_fragment(self):
  762. scheme, netloc, path, query, fragment = urlparse.urlsplit(self.url)
  763. return urlparse.urlunsplit((scheme, netloc, path, query, None))
  764. _egg_fragment_re = re.compile(r'#egg=([^&]*)')
  765. @property
  766. def egg_fragment(self):
  767. match = self._egg_fragment_re.search(self.url)
  768. if not match:
  769. return None
  770. return match.group(1)
  771. _hash_re = re.compile(r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)')
  772. @property
  773. def hash(self):
  774. match = self._hash_re.search(self.url)
  775. if match:
  776. return match.group(2)
  777. return None
  778. @property
  779. def hash_name(self):
  780. match = self._hash_re.search(self.url)
  781. if match:
  782. return match.group(1)
  783. return None
  784. @property
  785. def show_url(self):
  786. return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0])
  787. @property
  788. def verifiable(self):
  789. """
  790. Returns True if this link can be verified after download, False if it
  791. cannot, and None if we cannot determine.
  792. """
  793. trusted = self.trusted or getattr(self.comes_from, "trusted", None)
  794. if trusted is not None and trusted:
  795. # This link came from a trusted source. It *may* be verifiable but
  796. # first we need to see if this page is operating under the new
  797. # API version.
  798. try:
  799. api_version = getattr(self.comes_from, "api_version", None)
  800. api_version = int(api_version)
  801. except (ValueError, TypeError):
  802. api_version = None
  803. if api_version is None or api_version <= 1:
  804. # This link is either trusted, or it came from a trusted,
  805. # however it is not operating under the API version 2 so
  806. # we can't make any claims about if it's safe or not
  807. return
  808. if self.hash:
  809. # This link came from a trusted source and it has a hash, so we
  810. # can consider it safe.
  811. return True
  812. else:
  813. # This link came from a trusted source, using the new API
  814. # version, and it does not have a hash. It is NOT verifiable
  815. return False
  816. elif trusted is not None:
  817. # This link came from an untrusted source and we cannot trust it
  818. return False
  819. # An object to represent the "link" for the installed version of a requirement.
  820. # Using Inf as the url makes it sort higher.
  821. INSTALLED_VERSION = Link(Inf)
  822. def get_requirement_from_url(url):
  823. """Get a requirement from the URL, if possible. This looks for #egg
  824. in the URL"""
  825. link = Link(url)
  826. egg_info = link.egg_fragment
  827. if not egg_info:
  828. egg_info = splitext(link.filename)[0]
  829. return package_to_requirement(egg_info)
  830. def package_to_requirement(package_name):
  831. """Translate a name like Foo-1.2 to Foo==1.3"""
  832. match = re.search(r'^(.*?)-(dev|\d.*)', package_name)
  833. if match:
  834. name = match.group(1)
  835. version = match.group(2)
  836. else:
  837. name = package_name
  838. version = ''
  839. if version:
  840. return '%s==%s' % (name, version)
  841. else:
  842. return name