package_index.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. """PyPI and direct package downloading"""
  2. import sys
  3. import os
  4. import re
  5. import shutil
  6. import socket
  7. import base64
  8. import hashlib
  9. import itertools
  10. import warnings
  11. from functools import wraps
  12. from setuptools.extern import six
  13. from setuptools.extern.six.moves import urllib, http_client, configparser, map
  14. import setuptools
  15. from pkg_resources import (
  16. CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
  17. Environment, find_distributions, safe_name, safe_version,
  18. to_filename, Requirement, DEVELOP_DIST, EGG_DIST,
  19. )
  20. from setuptools import ssl_support
  21. from distutils import log
  22. from distutils.errors import DistutilsError
  23. from fnmatch import translate
  24. from setuptools.py27compat import get_all_headers
  25. from setuptools.py33compat import unescape
  26. from setuptools.wheel import Wheel
  27. __metaclass__ = type
  28. EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
  29. HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
  30. PYPI_MD5 = re.compile(
  31. r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)'
  32. r'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\)'
  33. )
  34. URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
  35. EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
  36. __all__ = [
  37. 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst',
  38. 'interpret_distro_name',
  39. ]
  40. _SOCKET_TIMEOUT = 15
  41. _tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
  42. user_agent = _tmpl.format(
  43. py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools)
  44. def parse_requirement_arg(spec):
  45. try:
  46. return Requirement.parse(spec)
  47. except ValueError as e:
  48. raise DistutilsError(
  49. "Not a URL, existing file, or requirement spec: %r" % (spec,)
  50. ) from e
  51. def parse_bdist_wininst(name):
  52. """Return (base,pyversion) or (None,None) for possible .exe name"""
  53. lower = name.lower()
  54. base, py_ver, plat = None, None, None
  55. if lower.endswith('.exe'):
  56. if lower.endswith('.win32.exe'):
  57. base = name[:-10]
  58. plat = 'win32'
  59. elif lower.startswith('.win32-py', -16):
  60. py_ver = name[-7:-4]
  61. base = name[:-16]
  62. plat = 'win32'
  63. elif lower.endswith('.win-amd64.exe'):
  64. base = name[:-14]
  65. plat = 'win-amd64'
  66. elif lower.startswith('.win-amd64-py', -20):
  67. py_ver = name[-7:-4]
  68. base = name[:-20]
  69. plat = 'win-amd64'
  70. return base, py_ver, plat
  71. def egg_info_for_url(url):
  72. parts = urllib.parse.urlparse(url)
  73. scheme, server, path, parameters, query, fragment = parts
  74. base = urllib.parse.unquote(path.split('/')[-1])
  75. if server == 'sourceforge.net' and base == 'download': # XXX Yuck
  76. base = urllib.parse.unquote(path.split('/')[-2])
  77. if '#' in base:
  78. base, fragment = base.split('#', 1)
  79. return base, fragment
  80. def distros_for_url(url, metadata=None):
  81. """Yield egg or source distribution objects that might be found at a URL"""
  82. base, fragment = egg_info_for_url(url)
  83. for dist in distros_for_location(url, base, metadata):
  84. yield dist
  85. if fragment:
  86. match = EGG_FRAGMENT.match(fragment)
  87. if match:
  88. for dist in interpret_distro_name(
  89. url, match.group(1), metadata, precedence=CHECKOUT_DIST
  90. ):
  91. yield dist
  92. def distros_for_location(location, basename, metadata=None):
  93. """Yield egg or source distribution objects based on basename"""
  94. if basename.endswith('.egg.zip'):
  95. basename = basename[:-4] # strip the .zip
  96. if basename.endswith('.egg') and '-' in basename:
  97. # only one, unambiguous interpretation
  98. return [Distribution.from_location(location, basename, metadata)]
  99. if basename.endswith('.whl') and '-' in basename:
  100. wheel = Wheel(basename)
  101. if not wheel.is_compatible():
  102. return []
  103. return [Distribution(
  104. location=location,
  105. project_name=wheel.project_name,
  106. version=wheel.version,
  107. # Increase priority over eggs.
  108. precedence=EGG_DIST + 1,
  109. )]
  110. if basename.endswith('.exe'):
  111. win_base, py_ver, platform = parse_bdist_wininst(basename)
  112. if win_base is not None:
  113. return interpret_distro_name(
  114. location, win_base, metadata, py_ver, BINARY_DIST, platform
  115. )
  116. # Try source distro extensions (.zip, .tgz, etc.)
  117. #
  118. for ext in EXTENSIONS:
  119. if basename.endswith(ext):
  120. basename = basename[:-len(ext)]
  121. return interpret_distro_name(location, basename, metadata)
  122. return [] # no extension matched
  123. def distros_for_filename(filename, metadata=None):
  124. """Yield possible egg or source distribution objects based on a filename"""
  125. return distros_for_location(
  126. normalize_path(filename), os.path.basename(filename), metadata
  127. )
  128. def interpret_distro_name(
  129. location, basename, metadata, py_version=None, precedence=SOURCE_DIST,
  130. platform=None
  131. ):
  132. """Generate alternative interpretations of a source distro name
  133. Note: if `location` is a filesystem filename, you should call
  134. ``pkg_resources.normalize_path()`` on it before passing it to this
  135. routine!
  136. """
  137. # Generate alternative interpretations of a source distro name
  138. # Because some packages are ambiguous as to name/versions split
  139. # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
  140. # So, we generate each possible interepretation (e.g. "adns, python-1.1.0"
  141. # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
  142. # the spurious interpretations should be ignored, because in the event
  143. # there's also an "adns" package, the spurious "python-1.1.0" version will
  144. # compare lower than any numeric version number, and is therefore unlikely
  145. # to match a request for it. It's still a potential problem, though, and
  146. # in the long run PyPI and the distutils should go for "safe" names and
  147. # versions in distribution archive names (sdist and bdist).
  148. parts = basename.split('-')
  149. if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
  150. # it is a bdist_dumb, not an sdist -- bail out
  151. return
  152. for p in range(1, len(parts) + 1):
  153. yield Distribution(
  154. location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
  155. py_version=py_version, precedence=precedence,
  156. platform=platform
  157. )
  158. # From Python 2.7 docs
  159. def unique_everseen(iterable, key=None):
  160. "List unique elements, preserving order. Remember all elements ever seen."
  161. # unique_everseen('AAAABBBCCDAABBB') --> A B C D
  162. # unique_everseen('ABBCcAD', str.lower) --> A B C D
  163. seen = set()
  164. seen_add = seen.add
  165. if key is None:
  166. for element in six.moves.filterfalse(seen.__contains__, iterable):
  167. seen_add(element)
  168. yield element
  169. else:
  170. for element in iterable:
  171. k = key(element)
  172. if k not in seen:
  173. seen_add(k)
  174. yield element
  175. def unique_values(func):
  176. """
  177. Wrap a function returning an iterable such that the resulting iterable
  178. only ever yields unique items.
  179. """
  180. @wraps(func)
  181. def wrapper(*args, **kwargs):
  182. return unique_everseen(func(*args, **kwargs))
  183. return wrapper
  184. REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I)
  185. # this line is here to fix emacs' cruddy broken syntax highlighting
  186. @unique_values
  187. def find_external_links(url, page):
  188. """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
  189. for match in REL.finditer(page):
  190. tag, rel = match.groups()
  191. rels = set(map(str.strip, rel.lower().split(',')))
  192. if 'homepage' in rels or 'download' in rels:
  193. for match in HREF.finditer(tag):
  194. yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
  195. for tag in ("<th>Home Page", "<th>Download URL"):
  196. pos = page.find(tag)
  197. if pos != -1:
  198. match = HREF.search(page, pos)
  199. if match:
  200. yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
  201. class ContentChecker:
  202. """
  203. A null content checker that defines the interface for checking content
  204. """
  205. def feed(self, block):
  206. """
  207. Feed a block of data to the hash.
  208. """
  209. return
  210. def is_valid(self):
  211. """
  212. Check the hash. Return False if validation fails.
  213. """
  214. return True
  215. def report(self, reporter, template):
  216. """
  217. Call reporter with information about the checker (hash name)
  218. substituted into the template.
  219. """
  220. return
  221. class HashChecker(ContentChecker):
  222. pattern = re.compile(
  223. r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
  224. r'(?P<expected>[a-f0-9]+)'
  225. )
  226. def __init__(self, hash_name, expected):
  227. self.hash_name = hash_name
  228. self.hash = hashlib.new(hash_name)
  229. self.expected = expected
  230. @classmethod
  231. def from_url(cls, url):
  232. "Construct a (possibly null) ContentChecker from a URL"
  233. fragment = urllib.parse.urlparse(url)[-1]
  234. if not fragment:
  235. return ContentChecker()
  236. match = cls.pattern.search(fragment)
  237. if not match:
  238. return ContentChecker()
  239. return cls(**match.groupdict())
  240. def feed(self, block):
  241. self.hash.update(block)
  242. def is_valid(self):
  243. return self.hash.hexdigest() == self.expected
  244. def report(self, reporter, template):
  245. msg = template % self.hash_name
  246. return reporter(msg)
  247. class PackageIndex(Environment):
  248. """A distribution index that scans web pages for download URLs"""
  249. def __init__(
  250. self, index_url="https://pypi.org/simple/", hosts=('*',),
  251. ca_bundle=None, verify_ssl=True, *args, **kw
  252. ):
  253. Environment.__init__(self, *args, **kw)
  254. self.index_url = index_url + "/" [:not index_url.endswith('/')]
  255. self.scanned_urls = {}
  256. self.fetched_urls = {}
  257. self.package_pages = {}
  258. self.allows = re.compile('|'.join(map(translate, hosts))).match
  259. self.to_scan = []
  260. use_ssl = (
  261. verify_ssl
  262. and ssl_support.is_available
  263. and (ca_bundle or ssl_support.find_ca_bundle())
  264. )
  265. if use_ssl:
  266. self.opener = ssl_support.opener_for(ca_bundle)
  267. else:
  268. self.opener = urllib.request.urlopen
  269. def process_url(self, url, retrieve=False):
  270. """Evaluate a URL as a possible download, and maybe retrieve it"""
  271. if url in self.scanned_urls and not retrieve:
  272. return
  273. self.scanned_urls[url] = True
  274. if not URL_SCHEME(url):
  275. self.process_filename(url)
  276. return
  277. else:
  278. dists = list(distros_for_url(url))
  279. if dists:
  280. if not self.url_ok(url):
  281. return
  282. self.debug("Found link: %s", url)
  283. if dists or not retrieve or url in self.fetched_urls:
  284. list(map(self.add, dists))
  285. return # don't need the actual page
  286. if not self.url_ok(url):
  287. self.fetched_urls[url] = True
  288. return
  289. self.info("Reading %s", url)
  290. self.fetched_urls[url] = True # prevent multiple fetch attempts
  291. tmpl = "Download error on %s: %%s -- Some packages may not be found!"
  292. f = self.open_url(url, tmpl % url)
  293. if f is None:
  294. return
  295. if isinstance(f, urllib.error.HTTPError) and f.code == 401:
  296. self.info("Authentication error: %s" % f.msg)
  297. self.fetched_urls[f.url] = True
  298. if 'html' not in f.headers.get('content-type', '').lower():
  299. f.close() # not html, we can't process it
  300. return
  301. base = f.url # handle redirects
  302. page = f.read()
  303. if not isinstance(page, str):
  304. # In Python 3 and got bytes but want str.
  305. if isinstance(f, urllib.error.HTTPError):
  306. # Errors have no charset, assume latin1:
  307. charset = 'latin-1'
  308. else:
  309. charset = f.headers.get_param('charset') or 'latin-1'
  310. page = page.decode(charset, "ignore")
  311. f.close()
  312. for match in HREF.finditer(page):
  313. link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
  314. self.process_url(link)
  315. if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
  316. page = self.process_index(url, page)
  317. def process_filename(self, fn, nested=False):
  318. # process filenames or directories
  319. if not os.path.exists(fn):
  320. self.warn("Not found: %s", fn)
  321. return
  322. if os.path.isdir(fn) and not nested:
  323. path = os.path.realpath(fn)
  324. for item in os.listdir(path):
  325. self.process_filename(os.path.join(path, item), True)
  326. dists = distros_for_filename(fn)
  327. if dists:
  328. self.debug("Found: %s", fn)
  329. list(map(self.add, dists))
  330. def url_ok(self, url, fatal=False):
  331. s = URL_SCHEME(url)
  332. is_file = s and s.group(1).lower() == 'file'
  333. if is_file or self.allows(urllib.parse.urlparse(url)[1]):
  334. return True
  335. msg = (
  336. "\nNote: Bypassing %s (disallowed host; see "
  337. "http://bit.ly/2hrImnY for details).\n")
  338. if fatal:
  339. raise DistutilsError(msg % url)
  340. else:
  341. self.warn(msg, url)
  342. def scan_egg_links(self, search_path):
  343. dirs = filter(os.path.isdir, search_path)
  344. egg_links = (
  345. (path, entry)
  346. for path in dirs
  347. for entry in os.listdir(path)
  348. if entry.endswith('.egg-link')
  349. )
  350. list(itertools.starmap(self.scan_egg_link, egg_links))
  351. def scan_egg_link(self, path, entry):
  352. with open(os.path.join(path, entry)) as raw_lines:
  353. # filter non-empty lines
  354. lines = list(filter(None, map(str.strip, raw_lines)))
  355. if len(lines) != 2:
  356. # format is not recognized; punt
  357. return
  358. egg_path, setup_path = lines
  359. for dist in find_distributions(os.path.join(path, egg_path)):
  360. dist.location = os.path.join(path, *lines)
  361. dist.precedence = SOURCE_DIST
  362. self.add(dist)
  363. def process_index(self, url, page):
  364. """Process the contents of a PyPI page"""
  365. def scan(link):
  366. # Process a URL to see if it's for a package page
  367. if link.startswith(self.index_url):
  368. parts = list(map(
  369. urllib.parse.unquote, link[len(self.index_url):].split('/')
  370. ))
  371. if len(parts) == 2 and '#' not in parts[1]:
  372. # it's a package page, sanitize and index it
  373. pkg = safe_name(parts[0])
  374. ver = safe_version(parts[1])
  375. self.package_pages.setdefault(pkg.lower(), {})[link] = True
  376. return to_filename(pkg), to_filename(ver)
  377. return None, None
  378. # process an index page into the package-page index
  379. for match in HREF.finditer(page):
  380. try:
  381. scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
  382. except ValueError:
  383. pass
  384. pkg, ver = scan(url) # ensure this page is in the page index
  385. if pkg:
  386. # process individual package page
  387. for new_url in find_external_links(url, page):
  388. # Process the found URL
  389. base, frag = egg_info_for_url(new_url)
  390. if base.endswith('.py') and not frag:
  391. if ver:
  392. new_url += '#egg=%s-%s' % (pkg, ver)
  393. else:
  394. self.need_version_info(url)
  395. self.scan_url(new_url)
  396. return PYPI_MD5.sub(
  397. lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page
  398. )
  399. else:
  400. return "" # no sense double-scanning non-package pages
  401. def need_version_info(self, url):
  402. self.scan_all(
  403. "Page at %s links to .py file(s) without version info; an index "
  404. "scan is required.", url
  405. )
  406. def scan_all(self, msg=None, *args):
  407. if self.index_url not in self.fetched_urls:
  408. if msg:
  409. self.warn(msg, *args)
  410. self.info(
  411. "Scanning index of all packages (this may take a while)"
  412. )
  413. self.scan_url(self.index_url)
  414. def find_packages(self, requirement):
  415. self.scan_url(self.index_url + requirement.unsafe_name + '/')
  416. if not self.package_pages.get(requirement.key):
  417. # Fall back to safe version of the name
  418. self.scan_url(self.index_url + requirement.project_name + '/')
  419. if not self.package_pages.get(requirement.key):
  420. # We couldn't find the target package, so search the index page too
  421. self.not_found_in_index(requirement)
  422. for url in list(self.package_pages.get(requirement.key, ())):
  423. # scan each page that might be related to the desired package
  424. self.scan_url(url)
  425. def obtain(self, requirement, installer=None):
  426. self.prescan()
  427. self.find_packages(requirement)
  428. for dist in self[requirement.key]:
  429. if dist in requirement:
  430. return dist
  431. self.debug("%s does not match %s", requirement, dist)
  432. return super(PackageIndex, self).obtain(requirement, installer)
  433. def check_hash(self, checker, filename, tfp):
  434. """
  435. checker is a ContentChecker
  436. """
  437. checker.report(
  438. self.debug,
  439. "Validating %%s checksum for %s" % filename)
  440. if not checker.is_valid():
  441. tfp.close()
  442. os.unlink(filename)
  443. raise DistutilsError(
  444. "%s validation failed for %s; "
  445. "possible download problem?"
  446. % (checker.hash.name, os.path.basename(filename))
  447. )
  448. def add_find_links(self, urls):
  449. """Add `urls` to the list that will be prescanned for searches"""
  450. for url in urls:
  451. if (
  452. self.to_scan is None # if we have already "gone online"
  453. or not URL_SCHEME(url) # or it's a local file/directory
  454. or url.startswith('file:')
  455. or list(distros_for_url(url)) # or a direct package link
  456. ):
  457. # then go ahead and process it now
  458. self.scan_url(url)
  459. else:
  460. # otherwise, defer retrieval till later
  461. self.to_scan.append(url)
  462. def prescan(self):
  463. """Scan urls scheduled for prescanning (e.g. --find-links)"""
  464. if self.to_scan:
  465. list(map(self.scan_url, self.to_scan))
  466. self.to_scan = None # from now on, go ahead and process immediately
  467. def not_found_in_index(self, requirement):
  468. if self[requirement.key]: # we've seen at least one distro
  469. meth, msg = self.info, "Couldn't retrieve index page for %r"
  470. else: # no distros seen for this name, might be misspelled
  471. meth, msg = (
  472. self.warn,
  473. "Couldn't find index page for %r (maybe misspelled?)")
  474. meth(msg, requirement.unsafe_name)
  475. self.scan_all()
  476. def download(self, spec, tmpdir):
  477. """Locate and/or download `spec` to `tmpdir`, returning a local path
  478. `spec` may be a ``Requirement`` object, or a string containing a URL,
  479. an existing local filename, or a project/version requirement spec
  480. (i.e. the string form of a ``Requirement`` object). If it is the URL
  481. of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
  482. that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
  483. automatically created alongside the downloaded file.
  484. If `spec` is a ``Requirement`` object or a string containing a
  485. project/version requirement spec, this method returns the location of
  486. a matching distribution (possibly after downloading it to `tmpdir`).
  487. If `spec` is a locally existing file or directory name, it is simply
  488. returned unchanged. If `spec` is a URL, it is downloaded to a subpath
  489. of `tmpdir`, and the local filename is returned. Various errors may be
  490. raised if a problem occurs during downloading.
  491. """
  492. if not isinstance(spec, Requirement):
  493. scheme = URL_SCHEME(spec)
  494. if scheme:
  495. # It's a url, download it to tmpdir
  496. found = self._download_url(scheme.group(1), spec, tmpdir)
  497. base, fragment = egg_info_for_url(spec)
  498. if base.endswith('.py'):
  499. found = self.gen_setup(found, fragment, tmpdir)
  500. return found
  501. elif os.path.exists(spec):
  502. # Existing file or directory, just return it
  503. return spec
  504. else:
  505. spec = parse_requirement_arg(spec)
  506. return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
  507. def fetch_distribution(
  508. self, requirement, tmpdir, force_scan=False, source=False,
  509. develop_ok=False, local_index=None):
  510. """Obtain a distribution suitable for fulfilling `requirement`
  511. `requirement` must be a ``pkg_resources.Requirement`` instance.
  512. If necessary, or if the `force_scan` flag is set, the requirement is
  513. searched for in the (online) package index as well as the locally
  514. installed packages. If a distribution matching `requirement` is found,
  515. the returned distribution's ``location`` is the value you would have
  516. gotten from calling the ``download()`` method with the matching
  517. distribution's URL or filename. If no matching distribution is found,
  518. ``None`` is returned.
  519. If the `source` flag is set, only source distributions and source
  520. checkout links will be considered. Unless the `develop_ok` flag is
  521. set, development and system eggs (i.e., those using the ``.egg-info``
  522. format) will be ignored.
  523. """
  524. # process a Requirement
  525. self.info("Searching for %s", requirement)
  526. skipped = {}
  527. dist = None
  528. def find(req, env=None):
  529. if env is None:
  530. env = self
  531. # Find a matching distribution; may be called more than once
  532. for dist in env[req.key]:
  533. if dist.precedence == DEVELOP_DIST and not develop_ok:
  534. if dist not in skipped:
  535. self.warn(
  536. "Skipping development or system egg: %s", dist,
  537. )
  538. skipped[dist] = 1
  539. continue
  540. test = (
  541. dist in req
  542. and (dist.precedence <= SOURCE_DIST or not source)
  543. )
  544. if test:
  545. loc = self.download(dist.location, tmpdir)
  546. dist.download_location = loc
  547. if os.path.exists(dist.download_location):
  548. return dist
  549. if force_scan:
  550. self.prescan()
  551. self.find_packages(requirement)
  552. dist = find(requirement)
  553. if not dist and local_index is not None:
  554. dist = find(requirement, local_index)
  555. if dist is None:
  556. if self.to_scan is not None:
  557. self.prescan()
  558. dist = find(requirement)
  559. if dist is None and not force_scan:
  560. self.find_packages(requirement)
  561. dist = find(requirement)
  562. if dist is None:
  563. self.warn(
  564. "No local packages or working download links found for %s%s",
  565. (source and "a source distribution of " or ""),
  566. requirement,
  567. )
  568. else:
  569. self.info("Best match: %s", dist)
  570. return dist.clone(location=dist.download_location)
  571. def fetch(self, requirement, tmpdir, force_scan=False, source=False):
  572. """Obtain a file suitable for fulfilling `requirement`
  573. DEPRECATED; use the ``fetch_distribution()`` method now instead. For
  574. backward compatibility, this routine is identical but returns the
  575. ``location`` of the downloaded distribution instead of a distribution
  576. object.
  577. """
  578. dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
  579. if dist is not None:
  580. return dist.location
  581. return None
  582. def gen_setup(self, filename, fragment, tmpdir):
  583. match = EGG_FRAGMENT.match(fragment)
  584. dists = match and [
  585. d for d in
  586. interpret_distro_name(filename, match.group(1), None) if d.version
  587. ] or []
  588. if len(dists) == 1: # unambiguous ``#egg`` fragment
  589. basename = os.path.basename(filename)
  590. # Make sure the file has been downloaded to the temp dir.
  591. if os.path.dirname(filename) != tmpdir:
  592. dst = os.path.join(tmpdir, basename)
  593. from setuptools.command.easy_install import samefile
  594. if not samefile(filename, dst):
  595. shutil.copy2(filename, dst)
  596. filename = dst
  597. with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
  598. file.write(
  599. "from setuptools import setup\n"
  600. "setup(name=%r, version=%r, py_modules=[%r])\n"
  601. % (
  602. dists[0].project_name, dists[0].version,
  603. os.path.splitext(basename)[0]
  604. )
  605. )
  606. return filename
  607. elif match:
  608. raise DistutilsError(
  609. "Can't unambiguously interpret project/version identifier %r; "
  610. "any dashes in the name or version should be escaped using "
  611. "underscores. %r" % (fragment, dists)
  612. )
  613. else:
  614. raise DistutilsError(
  615. "Can't process plain .py files without an '#egg=name-version'"
  616. " suffix to enable automatic setup script generation."
  617. )
  618. dl_blocksize = 8192
  619. def _download_to(self, url, filename):
  620. self.info("Downloading %s", url)
  621. # Download the file
  622. fp = None
  623. try:
  624. checker = HashChecker.from_url(url)
  625. fp = self.open_url(url)
  626. if isinstance(fp, urllib.error.HTTPError):
  627. raise DistutilsError(
  628. "Can't download %s: %s %s" % (url, fp.code, fp.msg)
  629. )
  630. headers = fp.info()
  631. blocknum = 0
  632. bs = self.dl_blocksize
  633. size = -1
  634. if "content-length" in headers:
  635. # Some servers return multiple Content-Length headers :(
  636. sizes = get_all_headers(headers, 'Content-Length')
  637. size = max(map(int, sizes))
  638. self.reporthook(url, filename, blocknum, bs, size)
  639. with open(filename, 'wb') as tfp:
  640. while True:
  641. block = fp.read(bs)
  642. if block:
  643. checker.feed(block)
  644. tfp.write(block)
  645. blocknum += 1
  646. self.reporthook(url, filename, blocknum, bs, size)
  647. else:
  648. break
  649. self.check_hash(checker, filename, tfp)
  650. return headers
  651. finally:
  652. if fp:
  653. fp.close()
  654. def reporthook(self, url, filename, blocknum, blksize, size):
  655. pass # no-op
  656. def open_url(self, url, warning=None):
  657. if url.startswith('file:'):
  658. return local_open(url)
  659. try:
  660. return open_with_auth(url, self.opener)
  661. except (ValueError, http_client.InvalidURL) as v:
  662. msg = ' '.join([str(arg) for arg in v.args])
  663. if warning:
  664. self.warn(warning, msg)
  665. else:
  666. raise DistutilsError('%s %s' % (url, msg)) from v
  667. except urllib.error.HTTPError as v:
  668. return v
  669. except urllib.error.URLError as v:
  670. if warning:
  671. self.warn(warning, v.reason)
  672. else:
  673. raise DistutilsError("Download error for %s: %s"
  674. % (url, v.reason)) from v
  675. except http_client.BadStatusLine as v:
  676. if warning:
  677. self.warn(warning, v.line)
  678. else:
  679. raise DistutilsError(
  680. '%s returned a bad status line. The server might be '
  681. 'down, %s' %
  682. (url, v.line)
  683. ) from v
  684. except (http_client.HTTPException, socket.error) as v:
  685. if warning:
  686. self.warn(warning, v)
  687. else:
  688. raise DistutilsError("Download error for %s: %s"
  689. % (url, v)) from v
  690. def _download_url(self, scheme, url, tmpdir):
  691. # Determine download filename
  692. #
  693. name, fragment = egg_info_for_url(url)
  694. if name:
  695. while '..' in name:
  696. name = name.replace('..', '.').replace('\\', '_')
  697. else:
  698. name = "__downloaded__" # default if URL has no path contents
  699. if name.endswith('.egg.zip'):
  700. name = name[:-4] # strip the extra .zip before download
  701. filename = os.path.join(tmpdir, name)
  702. # Download the file
  703. #
  704. if scheme == 'svn' or scheme.startswith('svn+'):
  705. return self._download_svn(url, filename)
  706. elif scheme == 'git' or scheme.startswith('git+'):
  707. return self._download_git(url, filename)
  708. elif scheme.startswith('hg+'):
  709. return self._download_hg(url, filename)
  710. elif scheme == 'file':
  711. return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
  712. else:
  713. self.url_ok(url, True) # raises error if not allowed
  714. return self._attempt_download(url, filename)
  715. def scan_url(self, url):
  716. self.process_url(url, True)
  717. def _attempt_download(self, url, filename):
  718. headers = self._download_to(url, filename)
  719. if 'html' in headers.get('content-type', '').lower():
  720. return self._download_html(url, headers, filename)
  721. else:
  722. return filename
  723. def _download_html(self, url, headers, filename):
  724. file = open(filename)
  725. for line in file:
  726. if line.strip():
  727. # Check for a subversion index page
  728. if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
  729. # it's a subversion index page:
  730. file.close()
  731. os.unlink(filename)
  732. return self._download_svn(url, filename)
  733. break # not an index page
  734. file.close()
  735. os.unlink(filename)
  736. raise DistutilsError("Unexpected HTML page found at " + url)
  737. def _download_svn(self, url, filename):
  738. warnings.warn("SVN download support is deprecated", UserWarning)
  739. url = url.split('#', 1)[0] # remove any fragment for svn's sake
  740. creds = ''
  741. if url.lower().startswith('svn:') and '@' in url:
  742. scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
  743. if not netloc and path.startswith('//') and '/' in path[2:]:
  744. netloc, path = path[2:].split('/', 1)
  745. auth, host = _splituser(netloc)
  746. if auth:
  747. if ':' in auth:
  748. user, pw = auth.split(':', 1)
  749. creds = " --username=%s --password=%s" % (user, pw)
  750. else:
  751. creds = " --username=" + auth
  752. netloc = host
  753. parts = scheme, netloc, url, p, q, f
  754. url = urllib.parse.urlunparse(parts)
  755. self.info("Doing subversion checkout from %s to %s", url, filename)
  756. os.system("svn checkout%s -q %s %s" % (creds, url, filename))
  757. return filename
  758. @staticmethod
  759. def _vcs_split_rev_from_url(url, pop_prefix=False):
  760. scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
  761. scheme = scheme.split('+', 1)[-1]
  762. # Some fragment identification fails
  763. path = path.split('#', 1)[0]
  764. rev = None
  765. if '@' in path:
  766. path, rev = path.rsplit('@', 1)
  767. # Also, discard fragment
  768. url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
  769. return url, rev
  770. def _download_git(self, url, filename):
  771. filename = filename.split('#', 1)[0]
  772. url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
  773. self.info("Doing git clone from %s to %s", url, filename)
  774. os.system("git clone --quiet %s %s" % (url, filename))
  775. if rev is not None:
  776. self.info("Checking out %s", rev)
  777. os.system("git -C %s checkout --quiet %s" % (
  778. filename,
  779. rev,
  780. ))
  781. return filename
  782. def _download_hg(self, url, filename):
  783. filename = filename.split('#', 1)[0]
  784. url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
  785. self.info("Doing hg clone from %s to %s", url, filename)
  786. os.system("hg clone --quiet %s %s" % (url, filename))
  787. if rev is not None:
  788. self.info("Updating to %s", rev)
  789. os.system("hg --cwd %s up -C -r %s -q" % (
  790. filename,
  791. rev,
  792. ))
  793. return filename
  794. def debug(self, msg, *args):
  795. log.debug(msg, *args)
  796. def info(self, msg, *args):
  797. log.info(msg, *args)
  798. def warn(self, msg, *args):
  799. log.warn(msg, *args)
  800. # This pattern matches a character entity reference (a decimal numeric
  801. # references, a hexadecimal numeric reference, or a named reference).
  802. entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
  803. def decode_entity(match):
  804. what = match.group(0)
  805. return unescape(what)
  806. def htmldecode(text):
  807. """
  808. Decode HTML entities in the given text.
  809. >>> htmldecode(
  810. ... 'https://../package_name-0.1.2.tar.gz'
  811. ... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz')
  812. 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
  813. """
  814. return entity_sub(decode_entity, text)
  815. def socket_timeout(timeout=15):
  816. def _socket_timeout(func):
  817. def _socket_timeout(*args, **kwargs):
  818. old_timeout = socket.getdefaulttimeout()
  819. socket.setdefaulttimeout(timeout)
  820. try:
  821. return func(*args, **kwargs)
  822. finally:
  823. socket.setdefaulttimeout(old_timeout)
  824. return _socket_timeout
  825. return _socket_timeout
  826. def _encode_auth(auth):
  827. """
  828. A function compatible with Python 2.3-3.3 that will encode
  829. auth from a URL suitable for an HTTP header.
  830. >>> str(_encode_auth('username%3Apassword'))
  831. 'dXNlcm5hbWU6cGFzc3dvcmQ='
  832. Long auth strings should not cause a newline to be inserted.
  833. >>> long_auth = 'username:' + 'password'*10
  834. >>> chr(10) in str(_encode_auth(long_auth))
  835. False
  836. """
  837. auth_s = urllib.parse.unquote(auth)
  838. # convert to bytes
  839. auth_bytes = auth_s.encode()
  840. encoded_bytes = base64.b64encode(auth_bytes)
  841. # convert back to a string
  842. encoded = encoded_bytes.decode()
  843. # strip the trailing carriage return
  844. return encoded.replace('\n', '')
  845. class Credential:
  846. """
  847. A username/password pair. Use like a namedtuple.
  848. """
  849. def __init__(self, username, password):
  850. self.username = username
  851. self.password = password
  852. def __iter__(self):
  853. yield self.username
  854. yield self.password
  855. def __str__(self):
  856. return '%(username)s:%(password)s' % vars(self)
  857. class PyPIConfig(configparser.RawConfigParser):
  858. def __init__(self):
  859. """
  860. Load from ~/.pypirc
  861. """
  862. defaults = dict.fromkeys(['username', 'password', 'repository'], '')
  863. configparser.RawConfigParser.__init__(self, defaults)
  864. rc = os.path.join(os.path.expanduser('~'), '.pypirc')
  865. if os.path.exists(rc):
  866. self.read(rc)
  867. @property
  868. def creds_by_repository(self):
  869. sections_with_repositories = [
  870. section for section in self.sections()
  871. if self.get(section, 'repository').strip()
  872. ]
  873. return dict(map(self._get_repo_cred, sections_with_repositories))
  874. def _get_repo_cred(self, section):
  875. repo = self.get(section, 'repository').strip()
  876. return repo, Credential(
  877. self.get(section, 'username').strip(),
  878. self.get(section, 'password').strip(),
  879. )
  880. def find_credential(self, url):
  881. """
  882. If the URL indicated appears to be a repository defined in this
  883. config, return the credential for that repository.
  884. """
  885. for repository, cred in self.creds_by_repository.items():
  886. if url.startswith(repository):
  887. return cred
  888. def open_with_auth(url, opener=urllib.request.urlopen):
  889. """Open a urllib2 request, handling HTTP authentication"""
  890. parsed = urllib.parse.urlparse(url)
  891. scheme, netloc, path, params, query, frag = parsed
  892. # Double scheme does not raise on macOS as revealed by a
  893. # failing test. We would expect "nonnumeric port". Refs #20.
  894. if netloc.endswith(':'):
  895. raise http_client.InvalidURL("nonnumeric port: ''")
  896. if scheme in ('http', 'https'):
  897. auth, address = _splituser(netloc)
  898. else:
  899. auth = None
  900. if not auth:
  901. cred = PyPIConfig().find_credential(url)
  902. if cred:
  903. auth = str(cred)
  904. info = cred.username, url
  905. log.info('Authenticating as %s for %s (from .pypirc)', *info)
  906. if auth:
  907. auth = "Basic " + _encode_auth(auth)
  908. parts = scheme, address, path, params, query, frag
  909. new_url = urllib.parse.urlunparse(parts)
  910. request = urllib.request.Request(new_url)
  911. request.add_header("Authorization", auth)
  912. else:
  913. request = urllib.request.Request(url)
  914. request.add_header('User-Agent', user_agent)
  915. fp = opener(request)
  916. if auth:
  917. # Put authentication info back into request URL if same host,
  918. # so that links found on the page will work
  919. s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
  920. if s2 == scheme and h2 == address:
  921. parts = s2, netloc, path2, param2, query2, frag2
  922. fp.url = urllib.parse.urlunparse(parts)
  923. return fp
  924. # copy of urllib.parse._splituser from Python 3.8
  925. def _splituser(host):
  926. """splituser('user[:passwd]@host[:port]')
  927. --> 'user[:passwd]', 'host[:port]'."""
  928. user, delim, host = host.rpartition('@')
  929. return (user if delim else None), host
  930. # adding a timeout to avoid freezing package_index
  931. open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
  932. def fix_sf_url(url):
  933. return url # backward compatibility
  934. def local_open(url):
  935. """Read a local path, with special support for directories"""
  936. scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
  937. filename = urllib.request.url2pathname(path)
  938. if os.path.isfile(filename):
  939. return urllib.request.urlopen(url)
  940. elif path.endswith('/') and os.path.isdir(filename):
  941. files = []
  942. for f in os.listdir(filename):
  943. filepath = os.path.join(filename, f)
  944. if f == 'index.html':
  945. with open(filepath, 'r') as fp:
  946. body = fp.read()
  947. break
  948. elif os.path.isdir(filepath):
  949. f += '/'
  950. files.append('<a href="{name}">{name}</a>'.format(name=f))
  951. else:
  952. tmpl = (
  953. "<html><head><title>{url}</title>"
  954. "</head><body>{files}</body></html>")
  955. body = tmpl.format(url=url, files='\n'.join(files))
  956. status, message = 200, "OK"
  957. else:
  958. status, message, body = 404, "Path not found", "Not found"
  959. headers = {'content-type': 'text/html'}
  960. body_stream = six.StringIO(body)
  961. return urllib.error.HTTPError(url, status, message, headers, body_stream)