package_index.py 39 KB

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