Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

locators.py 50KB

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