locators.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2014 Vinay Sajip.
  4. # Licensed to the Python Software Foundation under a contributor agreement.
  5. # See LICENSE.txt and CONTRIBUTORS.txt.
  6. #
  7. import gzip
  8. from io import BytesIO
  9. import json
  10. import logging
  11. import os
  12. import posixpath
  13. import re
  14. try:
  15. import threading
  16. except ImportError:
  17. import dummy_threading as threading
  18. import zlib
  19. from . import DistlibException
  20. from .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url,
  21. queue, quote, unescape, string_types, build_opener,
  22. HTTPRedirectHandler as BaseRedirectHandler,
  23. Request, HTTPError, URLError)
  24. from .database import Distribution, DistributionPath, make_dist
  25. from .metadata import Metadata
  26. from .util import (cached_property, parse_credentials, ensure_slash,
  27. split_filename, get_project_data, parse_requirement,
  28. parse_name_and_version, ServerProxy)
  29. from .version import get_scheme, UnsupportedVersionError
  30. from .wheel import Wheel, is_compatible
  31. logger = logging.getLogger(__name__)
  32. HASHER_HASH = re.compile('^(\w+)=([a-f0-9]+)')
  33. CHARSET = re.compile(r';\s*charset\s*=\s*(.*)\s*$', re.I)
  34. HTML_CONTENT_TYPE = re.compile('text/html|application/x(ht)?ml')
  35. DEFAULT_INDEX = 'http://python.org/pypi'
  36. def get_all_distribution_names(url=None):
  37. """
  38. Return all distribution names known by an index.
  39. :param url: The URL of the index.
  40. :return: A list of all known distribution names.
  41. """
  42. if url is None:
  43. url = DEFAULT_INDEX
  44. client = ServerProxy(url, timeout=3.0)
  45. return client.list_packages()
  46. class RedirectHandler(BaseRedirectHandler):
  47. """
  48. A class to work around a bug in some Python 3.2.x releases.
  49. """
  50. # There's a bug in the base version for some 3.2.x
  51. # (e.g. 3.2.2 on Ubuntu Oneiric). If a Location header
  52. # returns e.g. /abc, it bails because it says the scheme ''
  53. # is bogus, when actually it should use the request's
  54. # URL for the scheme. See Python issue #13696.
  55. def http_error_302(self, req, fp, code, msg, headers):
  56. # Some servers (incorrectly) return multiple Location headers
  57. # (so probably same goes for URI). Use first header.
  58. newurl = None
  59. for key in ('location', 'uri'):
  60. if key in headers:
  61. newurl = headers[key]
  62. break
  63. if newurl is None:
  64. return
  65. urlparts = urlparse(newurl)
  66. if urlparts.scheme == '':
  67. newurl = urljoin(req.get_full_url(), newurl)
  68. if hasattr(headers, 'replace_header'):
  69. headers.replace_header(key, newurl)
  70. else:
  71. headers[key] = newurl
  72. return BaseRedirectHandler.http_error_302(self, req, fp, code, msg,
  73. headers)
  74. http_error_301 = http_error_303 = http_error_307 = http_error_302
  75. class Locator(object):
  76. """
  77. A base class for locators - things that locate distributions.
  78. """
  79. source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz')
  80. binary_extensions = ('.egg', '.exe', '.whl')
  81. excluded_extensions = ('.pdf',)
  82. # A list of tags indicating which wheels you want to match. The default
  83. # value of None matches against the tags compatible with the running
  84. # Python. If you want to match other values, set wheel_tags on a locator
  85. # instance to a list of tuples (pyver, abi, arch) which you want to match.
  86. wheel_tags = None
  87. downloadable_extensions = source_extensions + ('.whl',)
  88. def __init__(self, scheme='default'):
  89. """
  90. Initialise an instance.
  91. :param scheme: Because locators look for most recent versions, they
  92. need to know the version scheme to use. This specifies
  93. the current PEP-recommended scheme - use ``'legacy'``
  94. if you need to support existing distributions on PyPI.
  95. """
  96. self._cache = {}
  97. self.scheme = scheme
  98. # Because of bugs in some of the handlers on some of the platforms,
  99. # we use our own opener rather than just using urlopen.
  100. self.opener = build_opener(RedirectHandler())
  101. # If get_project() is called from locate(), the matcher instance
  102. # is set from the requirement passed to locate(). See issue #18 for
  103. # why this can be useful to know.
  104. self.matcher = None
  105. def clear_cache(self):
  106. self._cache.clear()
  107. def _get_scheme(self):
  108. return self._scheme
  109. def _set_scheme(self, value):
  110. self._scheme = value
  111. scheme = property(_get_scheme, _set_scheme)
  112. def _get_project(self, name):
  113. """
  114. For a given project, get a dictionary mapping available versions to Distribution
  115. instances.
  116. This should be implemented in subclasses.
  117. If called from a locate() request, self.matcher will be set to a
  118. matcher for the requirement to satisfy, otherwise it will be None.
  119. """
  120. raise NotImplementedError('Please implement in the subclass')
  121. def get_distribution_names(self):
  122. """
  123. Return all the distribution names known to this locator.
  124. """
  125. raise NotImplementedError('Please implement in the subclass')
  126. def get_project(self, name):
  127. """
  128. For a given project, get a dictionary mapping available versions to Distribution
  129. instances.
  130. This calls _get_project to do all the work, and just implements a caching layer on top.
  131. """
  132. if self._cache is None:
  133. result = self._get_project(name)
  134. elif name in self._cache:
  135. result = self._cache[name]
  136. else:
  137. result = self._get_project(name)
  138. self._cache[name] = result
  139. return result
  140. def score_url(self, url):
  141. """
  142. Give an url a score which can be used to choose preferred URLs
  143. for a given project release.
  144. """
  145. t = urlparse(url)
  146. return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
  147. posixpath.basename(t.path))
  148. def prefer_url(self, url1, url2):
  149. """
  150. Choose one of two URLs where both are candidates for distribution
  151. archives for the same version of a distribution (for example,
  152. .tar.gz vs. zip).
  153. The current implement favours http:// URLs over https://, archives
  154. from PyPI over those from other locations and then the archive name.
  155. """
  156. result = url2
  157. if url1:
  158. s1 = self.score_url(url1)
  159. s2 = self.score_url(url2)
  160. if s1 > s2:
  161. result = url1
  162. if result != url2:
  163. logger.debug('Not replacing %r with %r', url1, url2)
  164. else:
  165. logger.debug('Replacing %r with %r', url1, url2)
  166. return result
  167. def split_filename(self, filename, project_name):
  168. """
  169. Attempt to split a filename in project name, version and Python version.
  170. """
  171. return split_filename(filename, project_name)
  172. def convert_url_to_download_info(self, url, project_name):
  173. """
  174. See if a URL is a candidate for a download URL for a project (the URL
  175. has typically been scraped from an HTML page).
  176. If it is, a dictionary is returned with keys "name", "version",
  177. "filename" and "url"; otherwise, None is returned.
  178. """
  179. def same_project(name1, name2):
  180. name1, name2 = name1.lower(), name2.lower()
  181. if name1 == name2:
  182. result = True
  183. else:
  184. # distribute replaces '-' by '_' in project names, so it
  185. # can tell where the version starts in a filename.
  186. result = name1.replace('_', '-') == name2.replace('_', '-')
  187. return result
  188. result = None
  189. scheme, netloc, path, params, query, frag = urlparse(url)
  190. if frag.lower().startswith('egg='):
  191. logger.debug('%s: version hint in fragment: %r',
  192. project_name, frag)
  193. m = HASHER_HASH.match(frag)
  194. if m:
  195. algo, digest = m.groups()
  196. else:
  197. algo, digest = None, None
  198. origpath = path
  199. if path and path[-1] == '/':
  200. path = path[:-1]
  201. if path.endswith('.whl'):
  202. try:
  203. wheel = Wheel(path)
  204. if is_compatible(wheel, self.wheel_tags):
  205. if project_name is None:
  206. include = True
  207. else:
  208. include = same_project(wheel.name, project_name)
  209. if include:
  210. result = {
  211. 'name': wheel.name,
  212. 'version': wheel.version,
  213. 'filename': wheel.filename,
  214. 'url': urlunparse((scheme, netloc, origpath,
  215. params, query, '')),
  216. 'python-version': ', '.join(
  217. ['.'.join(list(v[2:])) for v in wheel.pyver]),
  218. }
  219. except Exception as e:
  220. logger.warning('invalid path for wheel: %s', path)
  221. elif path.endswith(self.downloadable_extensions):
  222. path = filename = posixpath.basename(path)
  223. for ext in self.downloadable_extensions:
  224. if path.endswith(ext):
  225. path = path[:-len(ext)]
  226. t = self.split_filename(path, project_name)
  227. if not t:
  228. logger.debug('No match for project/version: %s', path)
  229. else:
  230. name, version, pyver = t
  231. if not project_name or same_project(project_name, name):
  232. result = {
  233. 'name': name,
  234. 'version': version,
  235. 'filename': filename,
  236. 'url': urlunparse((scheme, netloc, origpath,
  237. params, query, '')),
  238. #'packagetype': 'sdist',
  239. }
  240. if pyver:
  241. result['python-version'] = pyver
  242. break
  243. if result and algo:
  244. result['%s_digest' % algo] = digest
  245. return result
  246. def _get_digest(self, info):
  247. """
  248. Get a digest from a dictionary by looking at keys of the form
  249. 'algo_digest'.
  250. Returns a 2-tuple (algo, digest) if found, else None. Currently
  251. looks only for SHA256, then MD5.
  252. """
  253. result = None
  254. for algo in ('sha256', 'md5'):
  255. key = '%s_digest' % algo
  256. if key in info:
  257. result = (algo, info[key])
  258. break
  259. return result
  260. def _update_version_data(self, result, info):
  261. """
  262. Update a result dictionary (the final result from _get_project) with a
  263. dictionary for a specific version, which typically holds information
  264. gleaned from a filename or URL for an archive for the distribution.
  265. """
  266. name = info.pop('name')
  267. version = info.pop('version')
  268. if version in result:
  269. dist = result[version]
  270. md = dist.metadata
  271. else:
  272. dist = make_dist(name, version, scheme=self.scheme)
  273. md = dist.metadata
  274. dist.digest = digest = self._get_digest(info)
  275. url = info['url']
  276. result['digests'][url] = digest
  277. if md.source_url != info['url']:
  278. md.source_url = self.prefer_url(md.source_url, url)
  279. result['urls'].setdefault(version, set()).add(url)
  280. dist.locator = self
  281. result[version] = dist
  282. def locate(self, requirement, prereleases=False):
  283. """
  284. Find the most recent distribution which matches the given
  285. requirement.
  286. :param requirement: A requirement of the form 'foo (1.0)' or perhaps
  287. 'foo (>= 1.0, < 2.0, != 1.3)'
  288. :param prereleases: If ``True``, allow pre-release versions
  289. to be located. Otherwise, pre-release versions
  290. are not returned.
  291. :return: A :class:`Distribution` instance, or ``None`` if no such
  292. distribution could be located.
  293. """
  294. result = None
  295. r = parse_requirement(requirement)
  296. if r is None:
  297. raise DistlibException('Not a valid requirement: %r' % requirement)
  298. scheme = get_scheme(self.scheme)
  299. self.matcher = matcher = scheme.matcher(r.requirement)
  300. logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
  301. versions = self.get_project(r.name)
  302. if versions:
  303. # sometimes, versions are invalid
  304. slist = []
  305. vcls = matcher.version_class
  306. for k in versions:
  307. try:
  308. if not matcher.match(k):
  309. logger.debug('%s did not match %r', matcher, k)
  310. else:
  311. if prereleases or not vcls(k).is_prerelease:
  312. slist.append(k)
  313. else:
  314. logger.debug('skipping pre-release '
  315. 'version %s of %s', k, matcher.name)
  316. except Exception:
  317. logger.warning('error matching %s with %r', matcher, k)
  318. pass # slist.append(k)
  319. if len(slist) > 1:
  320. slist = sorted(slist, key=scheme.key)
  321. if slist:
  322. logger.debug('sorted list: %s', slist)
  323. version = slist[-1]
  324. result = versions[version]
  325. if result:
  326. if r.extras:
  327. result.extras = r.extras
  328. result.download_urls = versions.get('urls', {}).get(version, set())
  329. d = {}
  330. sd = versions.get('digests', {})
  331. for url in result.download_urls:
  332. if url in sd:
  333. d[url] = sd[url]
  334. result.digests = d
  335. self.matcher = None
  336. return result
  337. class PyPIRPCLocator(Locator):
  338. """
  339. This locator uses XML-RPC to locate distributions. It therefore
  340. cannot be used with simple mirrors (that only mirror file content).
  341. """
  342. def __init__(self, url, **kwargs):
  343. """
  344. Initialise an instance.
  345. :param url: The URL to use for XML-RPC.
  346. :param kwargs: Passed to the superclass constructor.
  347. """
  348. super(PyPIRPCLocator, self).__init__(**kwargs)
  349. self.base_url = url
  350. self.client = ServerProxy(url, timeout=3.0)
  351. def get_distribution_names(self):
  352. """
  353. Return all the distribution names known to this locator.
  354. """
  355. return set(self.client.list_packages())
  356. def _get_project(self, name):
  357. result = {'urls': {}, 'digests': {}}
  358. versions = self.client.package_releases(name, True)
  359. for v in versions:
  360. urls = self.client.release_urls(name, v)
  361. data = self.client.release_data(name, v)
  362. metadata = Metadata(scheme=self.scheme)
  363. metadata.name = data['name']
  364. metadata.version = data['version']
  365. metadata.license = data.get('license')
  366. metadata.keywords = data.get('keywords', [])
  367. metadata.summary = data.get('summary')
  368. dist = Distribution(metadata)
  369. if urls:
  370. info = urls[0]
  371. metadata.source_url = info['url']
  372. dist.digest = self._get_digest(info)
  373. dist.locator = self
  374. result[v] = dist
  375. for info in urls:
  376. url = info['url']
  377. digest = self._get_digest(info)
  378. result['urls'].setdefault(v, set()).add(url)
  379. result['digests'][url] = digest
  380. return result
  381. class PyPIJSONLocator(Locator):
  382. """
  383. This locator uses PyPI's JSON interface. It's very limited in functionality
  384. and probably not worth using.
  385. """
  386. def __init__(self, url, **kwargs):
  387. super(PyPIJSONLocator, self).__init__(**kwargs)
  388. self.base_url = ensure_slash(url)
  389. def get_distribution_names(self):
  390. """
  391. Return all the distribution names known to this locator.
  392. """
  393. raise NotImplementedError('Not available from this locator')
  394. def _get_project(self, name):
  395. result = {'urls': {}, 'digests': {}}
  396. url = urljoin(self.base_url, '%s/json' % quote(name))
  397. try:
  398. resp = self.opener.open(url)
  399. data = resp.read().decode() # for now
  400. d = json.loads(data)
  401. md = Metadata(scheme=self.scheme)
  402. data = d['info']
  403. md.name = data['name']
  404. md.version = data['version']
  405. md.license = data.get('license')
  406. md.keywords = data.get('keywords', [])
  407. md.summary = data.get('summary')
  408. dist = Distribution(md)
  409. urls = d['urls']
  410. if urls:
  411. info = urls[0]
  412. md.source_url = info['url']
  413. dist.digest = self._get_digest(info)
  414. dist.locator = self
  415. result[md.version] = dist
  416. for info in urls:
  417. url = info['url']
  418. result['urls'].setdefault(md.version, set()).add(url)
  419. result['digests'][url] = digest
  420. except Exception as e:
  421. logger.exception('JSON fetch failed: %s', e)
  422. return result
  423. class Page(object):
  424. """
  425. This class represents a scraped HTML page.
  426. """
  427. # The following slightly hairy-looking regex just looks for the contents of
  428. # an anchor link, which has an attribute "href" either immediately preceded
  429. # or immediately followed by a "rel" attribute. The attribute values can be
  430. # declared with double quotes, single quotes or no quotes - which leads to
  431. # the length of the expression.
  432. _href = re.compile("""
  433. (rel\s*=\s*(?:"(?P<rel1>[^"]*)"|'(?P<rel2>[^']*)'|(?P<rel3>[^>\s\n]*))\s+)?
  434. href\s*=\s*(?:"(?P<url1>[^"]*)"|'(?P<url2>[^']*)'|(?P<url3>[^>\s\n]*))
  435. (\s+rel\s*=\s*(?:"(?P<rel4>[^"]*)"|'(?P<rel5>[^']*)'|(?P<rel6>[^>\s\n]*)))?
  436. """, re.I | re.S | re.X)
  437. _base = re.compile(r"""<base\s+href\s*=\s*['"]?([^'">]+)""", re.I | re.S)
  438. def __init__(self, data, url):
  439. """
  440. Initialise an instance with the Unicode page contents and the URL they
  441. came from.
  442. """
  443. self.data = data
  444. self.base_url = self.url = url
  445. m = self._base.search(self.data)
  446. if m:
  447. self.base_url = m.group(1)
  448. _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
  449. @cached_property
  450. def links(self):
  451. """
  452. Return the URLs of all the links on a page together with information
  453. about their "rel" attribute, for determining which ones to treat as
  454. downloads and which ones to queue for further scraping.
  455. """
  456. def clean(url):
  457. "Tidy up an URL."
  458. scheme, netloc, path, params, query, frag = urlparse(url)
  459. return urlunparse((scheme, netloc, quote(path),
  460. params, query, frag))
  461. result = set()
  462. for match in self._href.finditer(self.data):
  463. d = match.groupdict('')
  464. rel = (d['rel1'] or d['rel2'] or d['rel3'] or
  465. d['rel4'] or d['rel5'] or d['rel6'])
  466. url = d['url1'] or d['url2'] or d['url3']
  467. url = urljoin(self.base_url, url)
  468. url = unescape(url)
  469. url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)
  470. result.add((url, rel))
  471. # We sort the result, hoping to bring the most recent versions
  472. # to the front
  473. result = sorted(result, key=lambda t: t[0], reverse=True)
  474. return result
  475. class SimpleScrapingLocator(Locator):
  476. """
  477. A locator which scrapes HTML pages to locate downloads for a distribution.
  478. This runs multiple threads to do the I/O; performance is at least as good
  479. as pip's PackageFinder, which works in an analogous fashion.
  480. """
  481. # These are used to deal with various Content-Encoding schemes.
  482. decoders = {
  483. 'deflate': zlib.decompress,
  484. 'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(d)).read(),
  485. 'none': lambda b: b,
  486. }
  487. def __init__(self, url, timeout=None, num_workers=10, **kwargs):
  488. """
  489. Initialise an instance.
  490. :param url: The root URL to use for scraping.
  491. :param timeout: The timeout, in seconds, to be applied to requests.
  492. This defaults to ``None`` (no timeout specified).
  493. :param num_workers: The number of worker threads you want to do I/O,
  494. This defaults to 10.
  495. :param kwargs: Passed to the superclass.
  496. """
  497. super(SimpleScrapingLocator, self).__init__(**kwargs)
  498. self.base_url = ensure_slash(url)
  499. self.timeout = timeout
  500. self._page_cache = {}
  501. self._seen = set()
  502. self._to_fetch = queue.Queue()
  503. self._bad_hosts = set()
  504. self.skip_externals = False
  505. self.num_workers = num_workers
  506. self._lock = threading.RLock()
  507. # See issue #45: we need to be resilient when the locator is used
  508. # in a thread, e.g. with concurrent.futures. We can't use self._lock
  509. # as it is for coordinating our internal threads - the ones created
  510. # in _prepare_threads.
  511. self._gplock = threading.RLock()
  512. def _prepare_threads(self):
  513. """
  514. Threads are created only when get_project is called, and terminate
  515. before it returns. They are there primarily to parallelise I/O (i.e.
  516. fetching web pages).
  517. """
  518. self._threads = []
  519. for i in range(self.num_workers):
  520. t = threading.Thread(target=self._fetch)
  521. t.setDaemon(True)
  522. t.start()
  523. self._threads.append(t)
  524. def _wait_threads(self):
  525. """
  526. Tell all the threads to terminate (by sending a sentinel value) and
  527. wait for them to do so.
  528. """
  529. # Note that you need two loops, since you can't say which
  530. # thread will get each sentinel
  531. for t in self._threads:
  532. self._to_fetch.put(None) # sentinel
  533. for t in self._threads:
  534. t.join()
  535. self._threads = []
  536. def _get_project(self, name):
  537. result = {'urls': {}, 'digests': {}}
  538. with self._gplock:
  539. self.result = result
  540. self.project_name = name
  541. url = urljoin(self.base_url, '%s/' % quote(name))
  542. self._seen.clear()
  543. self._page_cache.clear()
  544. self._prepare_threads()
  545. try:
  546. logger.debug('Queueing %s', url)
  547. self._to_fetch.put(url)
  548. self._to_fetch.join()
  549. finally:
  550. self._wait_threads()
  551. del self.result
  552. return result
  553. platform_dependent = re.compile(r'\b(linux-(i\d86|x86_64|arm\w+)|'
  554. r'win(32|-amd64)|macosx-?\d+)\b', re.I)
  555. def _is_platform_dependent(self, url):
  556. """
  557. Does an URL refer to a platform-specific download?
  558. """
  559. return self.platform_dependent.search(url)
  560. def _process_download(self, url):
  561. """
  562. See if an URL is a suitable download for a project.
  563. If it is, register information in the result dictionary (for
  564. _get_project) about the specific version it's for.
  565. Note that the return value isn't actually used other than as a boolean
  566. value.
  567. """
  568. if self._is_platform_dependent(url):
  569. info = None
  570. else:
  571. info = self.convert_url_to_download_info(url, self.project_name)
  572. logger.debug('process_download: %s -> %s', url, info)
  573. if info:
  574. with self._lock: # needed because self.result is shared
  575. self._update_version_data(self.result, info)
  576. return info
  577. def _should_queue(self, link, referrer, rel):
  578. """
  579. Determine whether a link URL from a referring page and with a
  580. particular "rel" attribute should be queued for scraping.
  581. """
  582. scheme, netloc, path, _, _, _ = urlparse(link)
  583. if path.endswith(self.source_extensions + self.binary_extensions +
  584. self.excluded_extensions):
  585. result = False
  586. elif self.skip_externals and not link.startswith(self.base_url):
  587. result = False
  588. elif not referrer.startswith(self.base_url):
  589. result = False
  590. elif rel not in ('homepage', 'download'):
  591. result = False
  592. elif scheme not in ('http', 'https', 'ftp'):
  593. result = False
  594. elif self._is_platform_dependent(link):
  595. result = False
  596. else:
  597. host = netloc.split(':', 1)[0]
  598. if host.lower() == 'localhost':
  599. result = False
  600. else:
  601. result = True
  602. logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,
  603. referrer, result)
  604. return result
  605. def _fetch(self):
  606. """
  607. Get a URL to fetch from the work queue, get the HTML page, examine its
  608. links for download candidates and candidates for further scraping.
  609. This is a handy method to run in a thread.
  610. """
  611. while True:
  612. url = self._to_fetch.get()
  613. try:
  614. if url:
  615. page = self.get_page(url)
  616. if page is None: # e.g. after an error
  617. continue
  618. for link, rel in page.links:
  619. if link not in self._seen:
  620. self._seen.add(link)
  621. if (not self._process_download(link) and
  622. self._should_queue(link, url, rel)):
  623. logger.debug('Queueing %s from %s', link, url)
  624. self._to_fetch.put(link)
  625. finally:
  626. # always do this, to avoid hangs :-)
  627. self._to_fetch.task_done()
  628. if not url:
  629. #logger.debug('Sentinel seen, quitting.')
  630. break
  631. def get_page(self, url):
  632. """
  633. Get the HTML for an URL, possibly from an in-memory cache.
  634. XXX TODO Note: this cache is never actually cleared. It's assumed that
  635. the data won't get stale over the lifetime of a locator instance (not
  636. necessarily true for the default_locator).
  637. """
  638. # http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
  639. scheme, netloc, path, _, _, _ = urlparse(url)
  640. if scheme == 'file' and os.path.isdir(url2pathname(path)):
  641. url = urljoin(ensure_slash(url), 'index.html')
  642. if url in self._page_cache:
  643. result = self._page_cache[url]
  644. logger.debug('Returning %s from cache: %s', url, result)
  645. else:
  646. host = netloc.split(':', 1)[0]
  647. result = None
  648. if host in self._bad_hosts:
  649. logger.debug('Skipping %s due to bad host %s', url, host)
  650. else:
  651. req = Request(url, headers={'Accept-encoding': 'identity'})
  652. try:
  653. logger.debug('Fetching %s', url)
  654. resp = self.opener.open(req, timeout=self.timeout)
  655. logger.debug('Fetched %s', url)
  656. headers = resp.info()
  657. content_type = headers.get('Content-Type', '')
  658. if HTML_CONTENT_TYPE.match(content_type):
  659. final_url = resp.geturl()
  660. data = resp.read()
  661. encoding = headers.get('Content-Encoding')
  662. if encoding:
  663. decoder = self.decoders[encoding] # fail if not found
  664. data = decoder(data)
  665. encoding = 'utf-8'
  666. m = CHARSET.search(content_type)
  667. if m:
  668. encoding = m.group(1)
  669. try:
  670. data = data.decode(encoding)
  671. except UnicodeError:
  672. data = data.decode('latin-1') # fallback
  673. result = Page(data, final_url)
  674. self._page_cache[final_url] = result
  675. except HTTPError as e:
  676. if e.code != 404:
  677. logger.exception('Fetch failed: %s: %s', url, e)
  678. except URLError as e:
  679. logger.exception('Fetch failed: %s: %s', url, e)
  680. with self._lock:
  681. self._bad_hosts.add(host)
  682. except Exception as e:
  683. logger.exception('Fetch failed: %s: %s', url, e)
  684. finally:
  685. self._page_cache[url] = result # even if None (failure)
  686. return result
  687. _distname_re = re.compile('<a href=[^>]*>([^<]+)<')
  688. def get_distribution_names(self):
  689. """
  690. Return all the distribution names known to this locator.
  691. """
  692. result = set()
  693. page = self.get_page(self.base_url)
  694. if not page:
  695. raise DistlibException('Unable to get %s' % self.base_url)
  696. for match in self._distname_re.finditer(page.data):
  697. result.add(match.group(1))
  698. return result
  699. class DirectoryLocator(Locator):
  700. """
  701. This class locates distributions in a directory tree.
  702. """
  703. def __init__(self, path, **kwargs):
  704. """
  705. Initialise an instance.
  706. :param path: The root of the directory tree to search.
  707. :param kwargs: Passed to the superclass constructor,
  708. except for:
  709. * recursive - if True (the default), subdirectories are
  710. recursed into. If False, only the top-level directory
  711. is searched,
  712. """
  713. self.recursive = kwargs.pop('recursive', True)
  714. super(DirectoryLocator, self).__init__(**kwargs)
  715. path = os.path.abspath(path)
  716. if not os.path.isdir(path):
  717. raise DistlibException('Not a directory: %r' % path)
  718. self.base_dir = path
  719. def should_include(self, filename, parent):
  720. """
  721. Should a filename be considered as a candidate for a distribution
  722. archive? As well as the filename, the directory which contains it
  723. is provided, though not used by the current implementation.
  724. """
  725. return filename.endswith(self.downloadable_extensions)
  726. def _get_project(self, name):
  727. result = {'urls': {}, 'digests': {}}
  728. for root, dirs, files in os.walk(self.base_dir):
  729. for fn in files:
  730. if self.should_include(fn, root):
  731. fn = os.path.join(root, fn)
  732. url = urlunparse(('file', '',
  733. pathname2url(os.path.abspath(fn)),
  734. '', '', ''))
  735. info = self.convert_url_to_download_info(url, name)
  736. if info:
  737. self._update_version_data(result, info)
  738. if not self.recursive:
  739. break
  740. return result
  741. def get_distribution_names(self):
  742. """
  743. Return all the distribution names known to this locator.
  744. """
  745. result = set()
  746. for root, dirs, files in os.walk(self.base_dir):
  747. for fn in files:
  748. if self.should_include(fn, root):
  749. fn = os.path.join(root, fn)
  750. url = urlunparse(('file', '',
  751. pathname2url(os.path.abspath(fn)),
  752. '', '', ''))
  753. info = self.convert_url_to_download_info(url, None)
  754. if info:
  755. result.add(info['name'])
  756. if not self.recursive:
  757. break
  758. return result
  759. class JSONLocator(Locator):
  760. """
  761. This locator uses special extended metadata (not available on PyPI) and is
  762. the basis of performant dependency resolution in distlib. Other locators
  763. require archive downloads before dependencies can be determined! As you
  764. might imagine, that can be slow.
  765. """
  766. def get_distribution_names(self):
  767. """
  768. Return all the distribution names known to this locator.
  769. """
  770. raise NotImplementedError('Not available from this locator')
  771. def _get_project(self, name):
  772. result = {'urls': {}, 'digests': {}}
  773. data = get_project_data(name)
  774. if data:
  775. for info in data.get('files', []):
  776. if info['ptype'] != 'sdist' or info['pyversion'] != 'source':
  777. continue
  778. # We don't store summary in project metadata as it makes
  779. # the data bigger for no benefit during dependency
  780. # resolution
  781. dist = make_dist(data['name'], info['version'],
  782. summary=data.get('summary',
  783. 'Placeholder for summary'),
  784. scheme=self.scheme)
  785. md = dist.metadata
  786. md.source_url = info['url']
  787. # TODO SHA256 digest
  788. if 'digest' in info and info['digest']:
  789. dist.digest = ('md5', info['digest'])
  790. md.dependencies = info.get('requirements', {})
  791. dist.exports = info.get('exports', {})
  792. result[dist.version] = dist
  793. result['urls'].setdefault(dist.version, set()).add(info['url'])
  794. return result
  795. class DistPathLocator(Locator):
  796. """
  797. This locator finds installed distributions in a path. It can be useful for
  798. adding to an :class:`AggregatingLocator`.
  799. """
  800. def __init__(self, distpath, **kwargs):
  801. """
  802. Initialise an instance.
  803. :param distpath: A :class:`DistributionPath` instance to search.
  804. """
  805. super(DistPathLocator, self).__init__(**kwargs)
  806. assert isinstance(distpath, DistributionPath)
  807. self.distpath = distpath
  808. def _get_project(self, name):
  809. dist = self.distpath.get_distribution(name)
  810. if dist is None:
  811. result = {}
  812. else:
  813. result = {
  814. dist.version: dist,
  815. 'urls': {dist.version: set([dist.source_url])}
  816. }
  817. return result
  818. class AggregatingLocator(Locator):
  819. """
  820. This class allows you to chain and/or merge a list of locators.
  821. """
  822. def __init__(self, *locators, **kwargs):
  823. """
  824. Initialise an instance.
  825. :param locators: The list of locators to search.
  826. :param kwargs: Passed to the superclass constructor,
  827. except for:
  828. * merge - if False (the default), the first successful
  829. search from any of the locators is returned. If True,
  830. the results from all locators are merged (this can be
  831. slow).
  832. """
  833. self.merge = kwargs.pop('merge', False)
  834. self.locators = locators
  835. super(AggregatingLocator, self).__init__(**kwargs)
  836. def clear_cache(self):
  837. super(AggregatingLocator, self).clear_cache()
  838. for locator in self.locators:
  839. locator.clear_cache()
  840. def _set_scheme(self, value):
  841. self._scheme = value
  842. for locator in self.locators:
  843. locator.scheme = value
  844. scheme = property(Locator.scheme.fget, _set_scheme)
  845. def _get_project(self, name):
  846. result = {}
  847. for locator in self.locators:
  848. d = locator.get_project(name)
  849. if d:
  850. if self.merge:
  851. files = result.get('urls', {})
  852. digests = result.get('digests', {})
  853. # next line could overwrite result['urls'], result['digests']
  854. result.update(d)
  855. df = result.get('urls')
  856. if files and df:
  857. for k, v in files.items():
  858. if k in df:
  859. df[k] |= v
  860. else:
  861. df[k] = v
  862. dd = result.get('digests')
  863. if digests and dd:
  864. dd.update(digests)
  865. else:
  866. # See issue #18. If any dists are found and we're looking
  867. # for specific constraints, we only return something if
  868. # a match is found. For example, if a DirectoryLocator
  869. # returns just foo (1.0) while we're looking for
  870. # foo (>= 2.0), we'll pretend there was nothing there so
  871. # that subsequent locators can be queried. Otherwise we
  872. # would just return foo (1.0) which would then lead to a
  873. # failure to find foo (>= 2.0), because other locators
  874. # weren't searched. Note that this only matters when
  875. # merge=False.
  876. if self.matcher is None:
  877. found = True
  878. else:
  879. found = False
  880. for k in d:
  881. if self.matcher.match(k):
  882. found = True
  883. break
  884. if found:
  885. result = d
  886. break
  887. return result
  888. def get_distribution_names(self):
  889. """
  890. Return all the distribution names known to this locator.
  891. """
  892. result = set()
  893. for locator in self.locators:
  894. try:
  895. result |= locator.get_distribution_names()
  896. except NotImplementedError:
  897. pass
  898. return result
  899. # We use a legacy scheme simply because most of the dists on PyPI use legacy
  900. # versions which don't conform to PEP 426 / PEP 440.
  901. default_locator = AggregatingLocator(
  902. JSONLocator(),
  903. SimpleScrapingLocator('https://pypi.python.org/simple/',
  904. timeout=3.0),
  905. scheme='legacy')
  906. locate = default_locator.locate
  907. NAME_VERSION_RE = re.compile(r'(?P<name>[\w-]+)\s*'
  908. r'\(\s*(==\s*)?(?P<ver>[^)]+)\)$')
  909. class DependencyFinder(object):
  910. """
  911. Locate dependencies for distributions.
  912. """
  913. def __init__(self, locator=None):
  914. """
  915. Initialise an instance, using the specified locator
  916. to locate distributions.
  917. """
  918. self.locator = locator or default_locator
  919. self.scheme = get_scheme(self.locator.scheme)
  920. def add_distribution(self, dist):
  921. """
  922. Add a distribution to the finder. This will update internal information
  923. about who provides what.
  924. :param dist: The distribution to add.
  925. """
  926. logger.debug('adding distribution %s', dist)
  927. name = dist.key
  928. self.dists_by_name[name] = dist
  929. self.dists[(name, dist.version)] = dist
  930. for p in dist.provides:
  931. name, version = parse_name_and_version(p)
  932. logger.debug('Add to provided: %s, %s, %s', name, version, dist)
  933. self.provided.setdefault(name, set()).add((version, dist))
  934. def remove_distribution(self, dist):
  935. """
  936. Remove a distribution from the finder. This will update internal
  937. information about who provides what.
  938. :param dist: The distribution to remove.
  939. """
  940. logger.debug('removing distribution %s', dist)
  941. name = dist.key
  942. del self.dists_by_name[name]
  943. del self.dists[(name, dist.version)]
  944. for p in dist.provides:
  945. name, version = parse_name_and_version(p)
  946. logger.debug('Remove from provided: %s, %s, %s', name, version, dist)
  947. s = self.provided[name]
  948. s.remove((version, dist))
  949. if not s:
  950. del self.provided[name]
  951. def get_matcher(self, reqt):
  952. """
  953. Get a version matcher for a requirement.
  954. :param reqt: The requirement
  955. :type reqt: str
  956. :return: A version matcher (an instance of
  957. :class:`distlib.version.Matcher`).
  958. """
  959. try:
  960. matcher = self.scheme.matcher(reqt)
  961. except UnsupportedVersionError:
  962. # XXX compat-mode if cannot read the version
  963. name = reqt.split()[0]
  964. matcher = self.scheme.matcher(name)
  965. return matcher
  966. def find_providers(self, reqt):
  967. """
  968. Find the distributions which can fulfill a requirement.
  969. :param reqt: The requirement.
  970. :type reqt: str
  971. :return: A set of distribution which can fulfill the requirement.
  972. """
  973. matcher = self.get_matcher(reqt)
  974. name = matcher.key # case-insensitive
  975. result = set()
  976. provided = self.provided
  977. if name in provided:
  978. for version, provider in provided[name]:
  979. try:
  980. match = matcher.match(version)
  981. except UnsupportedVersionError:
  982. match = False
  983. if match:
  984. result.add(provider)
  985. break
  986. return result
  987. def try_to_replace(self, provider, other, problems):
  988. """
  989. Attempt to replace one provider with another. This is typically used
  990. when resolving dependencies from multiple sources, e.g. A requires
  991. (B >= 1.0) while C requires (B >= 1.1).
  992. For successful replacement, ``provider`` must meet all the requirements
  993. which ``other`` fulfills.
  994. :param provider: The provider we are trying to replace with.
  995. :param other: The provider we're trying to replace.
  996. :param problems: If False is returned, this will contain what
  997. problems prevented replacement. This is currently
  998. a tuple of the literal string 'cantreplace',
  999. ``provider``, ``other`` and the set of requirements
  1000. that ``provider`` couldn't fulfill.
  1001. :return: True if we can replace ``other`` with ``provider``, else
  1002. False.
  1003. """
  1004. rlist = self.reqts[other]
  1005. unmatched = set()
  1006. for s in rlist:
  1007. matcher = self.get_matcher(s)
  1008. if not matcher.match(provider.version):
  1009. unmatched.add(s)
  1010. if unmatched:
  1011. # can't replace other with provider
  1012. problems.add(('cantreplace', provider, other,
  1013. frozenset(unmatched)))
  1014. result = False
  1015. else:
  1016. # can replace other with provider
  1017. self.remove_distribution(other)
  1018. del self.reqts[other]
  1019. for s in rlist:
  1020. self.reqts.setdefault(provider, set()).add(s)
  1021. self.add_distribution(provider)
  1022. result = True
  1023. return result
  1024. def find(self, requirement, meta_extras=None, prereleases=False):
  1025. """
  1026. Find a distribution and all distributions it depends on.
  1027. :param requirement: The requirement specifying the distribution to
  1028. find, or a Distribution instance.
  1029. :param meta_extras: A list of meta extras such as :test:, :build: and
  1030. so on.
  1031. :param prereleases: If ``True``, allow pre-release versions to be
  1032. returned - otherwise, don't return prereleases
  1033. unless they're all that's available.
  1034. Return a set of :class:`Distribution` instances and a set of
  1035. problems.
  1036. The distributions returned should be such that they have the
  1037. :attr:`required` attribute set to ``True`` if they were
  1038. from the ``requirement`` passed to ``find()``, and they have the
  1039. :attr:`build_time_dependency` attribute set to ``True`` unless they
  1040. are post-installation dependencies of the ``requirement``.
  1041. The problems should be a tuple consisting of the string
  1042. ``'unsatisfied'`` and the requirement which couldn't be satisfied
  1043. by any distribution known to the locator.
  1044. """
  1045. self.provided = {}
  1046. self.dists = {}
  1047. self.dists_by_name = {}
  1048. self.reqts = {}
  1049. meta_extras = set(meta_extras or [])
  1050. if ':*:' in meta_extras:
  1051. meta_extras.remove(':*:')
  1052. # :meta: and :run: are implicitly included
  1053. meta_extras |= set([':test:', ':build:', ':dev:'])
  1054. if isinstance(requirement, Distribution):
  1055. dist = odist = requirement
  1056. logger.debug('passed %s as requirement', odist)
  1057. else:
  1058. dist = odist = self.locator.locate(requirement,
  1059. prereleases=prereleases)
  1060. if dist is None:
  1061. raise DistlibException('Unable to locate %r' % requirement)
  1062. logger.debug('located %s', odist)
  1063. dist.requested = True
  1064. problems = set()
  1065. todo = set([dist])
  1066. install_dists = set([odist])
  1067. while todo:
  1068. dist = todo.pop()
  1069. name = dist.key # case-insensitive
  1070. if name not in self.dists_by_name:
  1071. self.add_distribution(dist)
  1072. else:
  1073. #import pdb; pdb.set_trace()
  1074. other = self.dists_by_name[name]
  1075. if other != dist:
  1076. self.try_to_replace(dist, other, problems)
  1077. ireqts = dist.run_requires | dist.meta_requires
  1078. sreqts = dist.build_requires
  1079. ereqts = set()
  1080. if dist in install_dists:
  1081. for key in ('test', 'build', 'dev'):
  1082. e = ':%s:' % key
  1083. if e in meta_extras:
  1084. ereqts |= getattr(dist, '%s_requires' % key)
  1085. all_reqts = ireqts | sreqts | ereqts
  1086. for r in all_reqts:
  1087. providers = self.find_providers(r)
  1088. if not providers:
  1089. logger.debug('No providers found for %r', r)
  1090. provider = self.locator.locate(r, prereleases=prereleases)
  1091. # If no provider is found and we didn't consider
  1092. # prereleases, consider them now.
  1093. if provider is None and not prereleases:
  1094. provider = self.locator.locate(r, prereleases=True)
  1095. if provider is None:
  1096. logger.debug('Cannot satisfy %r', r)
  1097. problems.add(('unsatisfied', r))
  1098. else:
  1099. n, v = provider.key, provider.version
  1100. if (n, v) not in self.dists:
  1101. todo.add(provider)
  1102. providers.add(provider)
  1103. if r in ireqts and dist in install_dists:
  1104. install_dists.add(provider)
  1105. logger.debug('Adding %s to install_dists',
  1106. provider.name_and_version)
  1107. for p in providers:
  1108. name = p.key
  1109. if name not in self.dists_by_name:
  1110. self.reqts.setdefault(p, set()).add(r)
  1111. else:
  1112. other = self.dists_by_name[name]
  1113. if other != p:
  1114. # see if other can be replaced by p
  1115. self.try_to_replace(p, other, problems)
  1116. dists = set(self.dists.values())
  1117. for dist in dists:
  1118. dist.build_time_dependency = dist not in install_dists
  1119. if dist.build_time_dependency:
  1120. logger.debug('%s is a build-time dependency only.',
  1121. dist.name_and_version)
  1122. logger.debug('find done for %s', odist)
  1123. return dists, problems