m2m模型翻译
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.

1303 lines
51 KiB

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