package_index.py 39 KB

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