locators.py 50 KB

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