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

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