Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

package_index.py 39KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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. __metaclass__ = type
  27. EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
  28. HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
  29. PYPI_MD5 = re.compile(
  30. r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)'
  31. r'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:
  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.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(0)
  800. return unescape(what)
  801. def htmldecode(text):
  802. """
  803. Decode HTML entities in the given text.
  804. >>> htmldecode(
  805. ... 'https://../package_name-0.1.2.tar.gz'
  806. ... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz')
  807. 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
  808. """
  809. return entity_sub(decode_entity, text)
  810. def socket_timeout(timeout=15):
  811. def _socket_timeout(func):
  812. def _socket_timeout(*args, **kwargs):
  813. old_timeout = socket.getdefaulttimeout()
  814. socket.setdefaulttimeout(timeout)
  815. try:
  816. return func(*args, **kwargs)
  817. finally:
  818. socket.setdefaulttimeout(old_timeout)
  819. return _socket_timeout
  820. return _socket_timeout
  821. def _encode_auth(auth):
  822. """
  823. A function compatible with Python 2.3-3.3 that will encode
  824. auth from a URL suitable for an HTTP header.
  825. >>> str(_encode_auth('username%3Apassword'))
  826. 'dXNlcm5hbWU6cGFzc3dvcmQ='
  827. Long auth strings should not cause a newline to be inserted.
  828. >>> long_auth = 'username:' + 'password'*10
  829. >>> chr(10) in str(_encode_auth(long_auth))
  830. False
  831. """
  832. auth_s = urllib.parse.unquote(auth)
  833. # convert to bytes
  834. auth_bytes = auth_s.encode()
  835. # use the legacy interface for Python 2.3 support
  836. encoded_bytes = base64.encodestring(auth_bytes)
  837. # convert back to a string
  838. encoded = encoded_bytes.decode()
  839. # strip the trailing carriage return
  840. return encoded.replace('\n', '')
  841. class Credential:
  842. """
  843. A username/password pair. Use like a namedtuple.
  844. """
  845. def __init__(self, username, password):
  846. self.username = username
  847. self.password = password
  848. def __iter__(self):
  849. yield self.username
  850. yield self.password
  851. def __str__(self):
  852. return '%(username)s:%(password)s' % vars(self)
  853. class PyPIConfig(configparser.RawConfigParser):
  854. def __init__(self):
  855. """
  856. Load from ~/.pypirc
  857. """
  858. defaults = dict.fromkeys(['username', 'password', 'repository'], '')
  859. configparser.RawConfigParser.__init__(self, defaults)
  860. rc = os.path.join(os.path.expanduser('~'), '.pypirc')
  861. if os.path.exists(rc):
  862. self.read(rc)
  863. @property
  864. def creds_by_repository(self):
  865. sections_with_repositories = [
  866. section for section in self.sections()
  867. if self.get(section, 'repository').strip()
  868. ]
  869. return dict(map(self._get_repo_cred, sections_with_repositories))
  870. def _get_repo_cred(self, section):
  871. repo = self.get(section, 'repository').strip()
  872. return repo, Credential(
  873. self.get(section, 'username').strip(),
  874. self.get(section, 'password').strip(),
  875. )
  876. def find_credential(self, url):
  877. """
  878. If the URL indicated appears to be a repository defined in this
  879. config, return the credential for that repository.
  880. """
  881. for repository, cred in self.creds_by_repository.items():
  882. if url.startswith(repository):
  883. return cred
  884. def open_with_auth(url, opener=urllib.request.urlopen):
  885. """Open a urllib2 request, handling HTTP authentication"""
  886. scheme, netloc, path, params, query, frag = urllib.parse.urlparse(url)
  887. # Double scheme does not raise on Mac OS X as revealed by a
  888. # failing test. We would expect "nonnumeric port". Refs #20.
  889. if netloc.endswith(':'):
  890. raise http_client.InvalidURL("nonnumeric port: ''")
  891. if scheme in ('http', 'https'):
  892. auth, host = urllib.parse.splituser(netloc)
  893. else:
  894. auth = None
  895. if not auth:
  896. cred = PyPIConfig().find_credential(url)
  897. if cred:
  898. auth = str(cred)
  899. info = cred.username, url
  900. log.info('Authenticating as %s for %s (from .pypirc)', *info)
  901. if auth:
  902. auth = "Basic " + _encode_auth(auth)
  903. parts = scheme, host, path, params, query, frag
  904. new_url = urllib.parse.urlunparse(parts)
  905. request = urllib.request.Request(new_url)
  906. request.add_header("Authorization", auth)
  907. else:
  908. request = urllib.request.Request(url)
  909. request.add_header('User-Agent', user_agent)
  910. fp = opener(request)
  911. if auth:
  912. # Put authentication info back into request URL if same host,
  913. # so that links found on the page will work
  914. s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
  915. if s2 == scheme and h2 == host:
  916. parts = s2, netloc, path2, param2, query2, frag2
  917. fp.url = urllib.parse.urlunparse(parts)
  918. return fp
  919. # adding a timeout to avoid freezing package_index
  920. open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
  921. def fix_sf_url(url):
  922. return url # backward compatibility
  923. def local_open(url):
  924. """Read a local path, with special support for directories"""
  925. scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
  926. filename = urllib.request.url2pathname(path)
  927. if os.path.isfile(filename):
  928. return urllib.request.urlopen(url)
  929. elif path.endswith('/') and os.path.isdir(filename):
  930. files = []
  931. for f in os.listdir(filename):
  932. filepath = os.path.join(filename, f)
  933. if f == 'index.html':
  934. with open(filepath, 'r') as fp:
  935. body = fp.read()
  936. break
  937. elif os.path.isdir(filepath):
  938. f += '/'
  939. files.append('<a href="{name}">{name}</a>'.format(name=f))
  940. else:
  941. tmpl = (
  942. "<html><head><title>{url}</title>"
  943. "</head><body>{files}</body></html>")
  944. body = tmpl.format(url=url, files='\n'.join(files))
  945. status, message = 200, "OK"
  946. else:
  947. status, message, body = 404, "Path not found", "Not found"
  948. headers = {'content-type': 'text/html'}
  949. body_stream = six.StringIO(body)
  950. return urllib.error.HTTPError(url, status, message, headers, body_stream)