package_index.py 38 KB

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