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.

1756 lines
58 KiB

4 years ago
  1. #
  2. # Copyright (C) 2012-2017 The Python Software Foundation.
  3. # See LICENSE.txt and CONTRIBUTORS.txt.
  4. #
  5. import codecs
  6. from collections import deque
  7. import contextlib
  8. import csv
  9. from glob import iglob as std_iglob
  10. import io
  11. import json
  12. import logging
  13. import os
  14. import py_compile
  15. import re
  16. import socket
  17. try:
  18. import ssl
  19. except ImportError: # pragma: no cover
  20. ssl = None
  21. import subprocess
  22. import sys
  23. import tarfile
  24. import tempfile
  25. import textwrap
  26. try:
  27. import threading
  28. except ImportError: # pragma: no cover
  29. import dummy_threading as threading
  30. import time
  31. from . import DistlibException
  32. from .compat import (string_types, text_type, shutil, raw_input, StringIO,
  33. cache_from_source, urlopen, urljoin, httplib, xmlrpclib,
  34. splittype, HTTPHandler, BaseConfigurator, valid_ident,
  35. Container, configparser, URLError, ZipFile, fsdecode,
  36. unquote, urlparse)
  37. logger = logging.getLogger(__name__)
  38. #
  39. # Requirement parsing code as per PEP 508
  40. #
  41. IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')
  42. VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')
  43. COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')
  44. MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')
  45. OR = re.compile(r'^or\b\s*')
  46. AND = re.compile(r'^and\b\s*')
  47. NON_SPACE = re.compile(r'(\S+)\s*')
  48. STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')
  49. def parse_marker(marker_string):
  50. """
  51. Parse a marker string and return a dictionary containing a marker expression.
  52. The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
  53. the expression grammar, or strings. A string contained in quotes is to be
  54. interpreted as a literal string, and a string not contained in quotes is a
  55. variable (such as os_name).
  56. """
  57. def marker_var(remaining):
  58. # either identifier, or literal string
  59. m = IDENTIFIER.match(remaining)
  60. if m:
  61. result = m.groups()[0]
  62. remaining = remaining[m.end():]
  63. elif not remaining:
  64. raise SyntaxError('unexpected end of input')
  65. else:
  66. q = remaining[0]
  67. if q not in '\'"':
  68. raise SyntaxError('invalid expression: %s' % remaining)
  69. oq = '\'"'.replace(q, '')
  70. remaining = remaining[1:]
  71. parts = [q]
  72. while remaining:
  73. # either a string chunk, or oq, or q to terminate
  74. if remaining[0] == q:
  75. break
  76. elif remaining[0] == oq:
  77. parts.append(oq)
  78. remaining = remaining[1:]
  79. else:
  80. m = STRING_CHUNK.match(remaining)
  81. if not m:
  82. raise SyntaxError('error in string literal: %s' % remaining)
  83. parts.append(m.groups()[0])
  84. remaining = remaining[m.end():]
  85. else:
  86. s = ''.join(parts)
  87. raise SyntaxError('unterminated string: %s' % s)
  88. parts.append(q)
  89. result = ''.join(parts)
  90. remaining = remaining[1:].lstrip() # skip past closing quote
  91. return result, remaining
  92. def marker_expr(remaining):
  93. if remaining and remaining[0] == '(':
  94. result, remaining = marker(remaining[1:].lstrip())
  95. if remaining[0] != ')':
  96. raise SyntaxError('unterminated parenthesis: %s' % remaining)
  97. remaining = remaining[1:].lstrip()
  98. else:
  99. lhs, remaining = marker_var(remaining)
  100. while remaining:
  101. m = MARKER_OP.match(remaining)
  102. if not m:
  103. break
  104. op = m.groups()[0]
  105. remaining = remaining[m.end():]
  106. rhs, remaining = marker_var(remaining)
  107. lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
  108. result = lhs
  109. return result, remaining
  110. def marker_and(remaining):
  111. lhs, remaining = marker_expr(remaining)
  112. while remaining:
  113. m = AND.match(remaining)
  114. if not m:
  115. break
  116. remaining = remaining[m.end():]
  117. rhs, remaining = marker_expr(remaining)
  118. lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
  119. return lhs, remaining
  120. def marker(remaining):
  121. lhs, remaining = marker_and(remaining)
  122. while remaining:
  123. m = OR.match(remaining)
  124. if not m:
  125. break
  126. remaining = remaining[m.end():]
  127. rhs, remaining = marker_and(remaining)
  128. lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
  129. return lhs, remaining
  130. return marker(marker_string)
  131. def parse_requirement(req):
  132. """
  133. Parse a requirement passed in as a string. Return a Container
  134. whose attributes contain the various parts of the requirement.
  135. """
  136. remaining = req.strip()
  137. if not remaining or remaining.startswith('#'):
  138. return None
  139. m = IDENTIFIER.match(remaining)
  140. if not m:
  141. raise SyntaxError('name expected: %s' % remaining)
  142. distname = m.groups()[0]
  143. remaining = remaining[m.end():]
  144. extras = mark_expr = versions = uri = None
  145. if remaining and remaining[0] == '[':
  146. i = remaining.find(']', 1)
  147. if i < 0:
  148. raise SyntaxError('unterminated extra: %s' % remaining)
  149. s = remaining[1:i]
  150. remaining = remaining[i + 1:].lstrip()
  151. extras = []
  152. while s:
  153. m = IDENTIFIER.match(s)
  154. if not m:
  155. raise SyntaxError('malformed extra: %s' % s)
  156. extras.append(m.groups()[0])
  157. s = s[m.end():]
  158. if not s:
  159. break
  160. if s[0] != ',':
  161. raise SyntaxError('comma expected in extras: %s' % s)
  162. s = s[1:].lstrip()
  163. if not extras:
  164. extras = None
  165. if remaining:
  166. if remaining[0] == '@':
  167. # it's a URI
  168. remaining = remaining[1:].lstrip()
  169. m = NON_SPACE.match(remaining)
  170. if not m:
  171. raise SyntaxError('invalid URI: %s' % remaining)
  172. uri = m.groups()[0]
  173. t = urlparse(uri)
  174. # there are issues with Python and URL parsing, so this test
  175. # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
  176. # always parse invalid URLs correctly - it should raise
  177. # exceptions for malformed URLs
  178. if not (t.scheme and t.netloc):
  179. raise SyntaxError('Invalid URL: %s' % uri)
  180. remaining = remaining[m.end():].lstrip()
  181. else:
  182. def get_versions(ver_remaining):
  183. """
  184. Return a list of operator, version tuples if any are
  185. specified, else None.
  186. """
  187. m = COMPARE_OP.match(ver_remaining)
  188. versions = None
  189. if m:
  190. versions = []
  191. while True:
  192. op = m.groups()[0]
  193. ver_remaining = ver_remaining[m.end():]
  194. m = VERSION_IDENTIFIER.match(ver_remaining)
  195. if not m:
  196. raise SyntaxError('invalid version: %s' % ver_remaining)
  197. v = m.groups()[0]
  198. versions.append((op, v))
  199. ver_remaining = ver_remaining[m.end():]
  200. if not ver_remaining or ver_remaining[0] != ',':
  201. break
  202. ver_remaining = ver_remaining[1:].lstrip()
  203. m = COMPARE_OP.match(ver_remaining)
  204. if not m:
  205. raise SyntaxError('invalid constraint: %s' % ver_remaining)
  206. if not versions:
  207. versions = None
  208. return versions, ver_remaining
  209. if remaining[0] != '(':
  210. versions, remaining = get_versions(remaining)
  211. else:
  212. i = remaining.find(')', 1)
  213. if i < 0:
  214. raise SyntaxError('unterminated parenthesis: %s' % remaining)
  215. s = remaining[1:i]
  216. remaining = remaining[i + 1:].lstrip()
  217. # As a special diversion from PEP 508, allow a version number
  218. # a.b.c in parentheses as a synonym for ~= a.b.c (because this
  219. # is allowed in earlier PEPs)
  220. if COMPARE_OP.match(s):
  221. versions, _ = get_versions(s)
  222. else:
  223. m = VERSION_IDENTIFIER.match(s)
  224. if not m:
  225. raise SyntaxError('invalid constraint: %s' % s)
  226. v = m.groups()[0]
  227. s = s[m.end():].lstrip()
  228. if s:
  229. raise SyntaxError('invalid constraint: %s' % s)
  230. versions = [('~=', v)]
  231. if remaining:
  232. if remaining[0] != ';':
  233. raise SyntaxError('invalid requirement: %s' % remaining)
  234. remaining = remaining[1:].lstrip()
  235. mark_expr, remaining = parse_marker(remaining)
  236. if remaining and remaining[0] != '#':
  237. raise SyntaxError('unexpected trailing data: %s' % remaining)
  238. if not versions:
  239. rs = distname
  240. else:
  241. rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
  242. return Container(name=distname, extras=extras, constraints=versions,
  243. marker=mark_expr, url=uri, requirement=rs)
  244. def get_resources_dests(resources_root, rules):
  245. """Find destinations for resources files"""
  246. def get_rel_path(root, path):
  247. # normalizes and returns a lstripped-/-separated path
  248. root = root.replace(os.path.sep, '/')
  249. path = path.replace(os.path.sep, '/')
  250. assert path.startswith(root)
  251. return path[len(root):].lstrip('/')
  252. destinations = {}
  253. for base, suffix, dest in rules:
  254. prefix = os.path.join(resources_root, base)
  255. for abs_base in iglob(prefix):
  256. abs_glob = os.path.join(abs_base, suffix)
  257. for abs_path in iglob(abs_glob):
  258. resource_file = get_rel_path(resources_root, abs_path)
  259. if dest is None: # remove the entry if it was here
  260. destinations.pop(resource_file, None)
  261. else:
  262. rel_path = get_rel_path(abs_base, abs_path)
  263. rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
  264. destinations[resource_file] = rel_dest + '/' + rel_path
  265. return destinations
  266. def in_venv():
  267. if hasattr(sys, 'real_prefix'):
  268. # virtualenv venvs
  269. result = True
  270. else:
  271. # PEP 405 venvs
  272. result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
  273. return result
  274. def get_executable():
  275. # The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as
  276. # changes to the stub launcher mean that sys.executable always points
  277. # to the stub on OS X
  278. # if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
  279. # in os.environ):
  280. # result = os.environ['__PYVENV_LAUNCHER__']
  281. # else:
  282. # result = sys.executable
  283. # return result
  284. result = os.path.normcase(sys.executable)
  285. if not isinstance(result, text_type):
  286. result = fsdecode(result)
  287. return result
  288. def proceed(prompt, allowed_chars, error_prompt=None, default=None):
  289. p = prompt
  290. while True:
  291. s = raw_input(p)
  292. p = prompt
  293. if not s and default:
  294. s = default
  295. if s:
  296. c = s[0].lower()
  297. if c in allowed_chars:
  298. break
  299. if error_prompt:
  300. p = '%c: %s\n%s' % (c, error_prompt, prompt)
  301. return c
  302. def extract_by_key(d, keys):
  303. if isinstance(keys, string_types):
  304. keys = keys.split()
  305. result = {}
  306. for key in keys:
  307. if key in d:
  308. result[key] = d[key]
  309. return result
  310. def read_exports(stream):
  311. if sys.version_info[0] >= 3:
  312. # needs to be a text stream
  313. stream = codecs.getreader('utf-8')(stream)
  314. # Try to load as JSON, falling back on legacy format
  315. data = stream.read()
  316. stream = StringIO(data)
  317. try:
  318. jdata = json.load(stream)
  319. result = jdata['extensions']['python.exports']['exports']
  320. for group, entries in result.items():
  321. for k, v in entries.items():
  322. s = '%s = %s' % (k, v)
  323. entry = get_export_entry(s)
  324. assert entry is not None
  325. entries[k] = entry
  326. return result
  327. except Exception:
  328. stream.seek(0, 0)
  329. def read_stream(cp, stream):
  330. if hasattr(cp, 'read_file'):
  331. cp.read_file(stream)
  332. else:
  333. cp.readfp(stream)
  334. cp = configparser.ConfigParser()
  335. try:
  336. read_stream(cp, stream)
  337. except configparser.MissingSectionHeaderError:
  338. stream.close()
  339. data = textwrap.dedent(data)
  340. stream = StringIO(data)
  341. read_stream(cp, stream)
  342. result = {}
  343. for key in cp.sections():
  344. result[key] = entries = {}
  345. for name, value in cp.items(key):
  346. s = '%s = %s' % (name, value)
  347. entry = get_export_entry(s)
  348. assert entry is not None
  349. #entry.dist = self
  350. entries[name] = entry
  351. return result
  352. def write_exports(exports, stream):
  353. if sys.version_info[0] >= 3:
  354. # needs to be a text stream
  355. stream = codecs.getwriter('utf-8')(stream)
  356. cp = configparser.ConfigParser()
  357. for k, v in exports.items():
  358. # TODO check k, v for valid values
  359. cp.add_section(k)
  360. for entry in v.values():
  361. if entry.suffix is None:
  362. s = entry.prefix
  363. else:
  364. s = '%s:%s' % (entry.prefix, entry.suffix)
  365. if entry.flags:
  366. s = '%s [%s]' % (s, ', '.join(entry.flags))
  367. cp.set(k, entry.name, s)
  368. cp.write(stream)
  369. @contextlib.contextmanager
  370. def tempdir():
  371. td = tempfile.mkdtemp()
  372. try:
  373. yield td
  374. finally:
  375. shutil.rmtree(td)
  376. @contextlib.contextmanager
  377. def chdir(d):
  378. cwd = os.getcwd()
  379. try:
  380. os.chdir(d)
  381. yield
  382. finally:
  383. os.chdir(cwd)
  384. @contextlib.contextmanager
  385. def socket_timeout(seconds=15):
  386. cto = socket.getdefaulttimeout()
  387. try:
  388. socket.setdefaulttimeout(seconds)
  389. yield
  390. finally:
  391. socket.setdefaulttimeout(cto)
  392. class cached_property(object):
  393. def __init__(self, func):
  394. self.func = func
  395. #for attr in ('__name__', '__module__', '__doc__'):
  396. # setattr(self, attr, getattr(func, attr, None))
  397. def __get__(self, obj, cls=None):
  398. if obj is None:
  399. return self
  400. value = self.func(obj)
  401. object.__setattr__(obj, self.func.__name__, value)
  402. #obj.__dict__[self.func.__name__] = value = self.func(obj)
  403. return value
  404. def convert_path(pathname):
  405. """Return 'pathname' as a name that will work on the native filesystem.
  406. The path is split on '/' and put back together again using the current
  407. directory separator. Needed because filenames in the setup script are
  408. always supplied in Unix style, and have to be converted to the local
  409. convention before we can actually use them in the filesystem. Raises
  410. ValueError on non-Unix-ish systems if 'pathname' either starts or
  411. ends with a slash.
  412. """
  413. if os.sep == '/':
  414. return pathname
  415. if not pathname:
  416. return pathname
  417. if pathname[0] == '/':
  418. raise ValueError("path '%s' cannot be absolute" % pathname)
  419. if pathname[-1] == '/':
  420. raise ValueError("path '%s' cannot end with '/'" % pathname)
  421. paths = pathname.split('/')
  422. while os.curdir in paths:
  423. paths.remove(os.curdir)
  424. if not paths:
  425. return os.curdir
  426. return os.path.join(*paths)
  427. class FileOperator(object):
  428. def __init__(self, dry_run=False):
  429. self.dry_run = dry_run
  430. self.ensured = set()
  431. self._init_record()
  432. def _init_record(self):
  433. self.record = False
  434. self.files_written = set()
  435. self.dirs_created = set()
  436. def record_as_written(self, path):
  437. if self.record:
  438. self.files_written.add(path)
  439. def newer(self, source, target):
  440. """Tell if the target is newer than the source.
  441. Returns true if 'source' exists and is more recently modified than
  442. 'target', or if 'source' exists and 'target' doesn't.
  443. Returns false if both exist and 'target' is the same age or younger
  444. than 'source'. Raise PackagingFileError if 'source' does not exist.
  445. Note that this test is not very accurate: files created in the same
  446. second will have the same "age".
  447. """
  448. if not os.path.exists(source):
  449. raise DistlibException("file '%r' does not exist" %
  450. os.path.abspath(source))
  451. if not os.path.exists(target):
  452. return True
  453. return os.stat(source).st_mtime > os.stat(target).st_mtime
  454. def copy_file(self, infile, outfile, check=True):
  455. """Copy a file respecting dry-run and force flags.
  456. """
  457. self.ensure_dir(os.path.dirname(outfile))
  458. logger.info('Copying %s to %s', infile, outfile)
  459. if not self.dry_run:
  460. msg = None
  461. if check:
  462. if os.path.islink(outfile):
  463. msg = '%s is a symlink' % outfile
  464. elif os.path.exists(outfile) and not os.path.isfile(outfile):
  465. msg = '%s is a non-regular file' % outfile
  466. if msg:
  467. raise ValueError(msg + ' which would be overwritten')
  468. shutil.copyfile(infile, outfile)
  469. self.record_as_written(outfile)
  470. def copy_stream(self, instream, outfile, encoding=None):
  471. assert not os.path.isdir(outfile)
  472. self.ensure_dir(os.path.dirname(outfile))
  473. logger.info('Copying stream %s to %s', instream, outfile)
  474. if not self.dry_run:
  475. if encoding is None:
  476. outstream = open(outfile, 'wb')
  477. else:
  478. outstream = codecs.open(outfile, 'w', encoding=encoding)
  479. try:
  480. shutil.copyfileobj(instream, outstream)
  481. finally:
  482. outstream.close()
  483. self.record_as_written(outfile)
  484. def write_binary_file(self, path, data):
  485. self.ensure_dir(os.path.dirname(path))
  486. if not self.dry_run:
  487. if os.path.exists(path):
  488. os.remove(path)
  489. with open(path, 'wb') as f:
  490. f.write(data)
  491. self.record_as_written(path)
  492. def write_text_file(self, path, data, encoding):
  493. self.write_binary_file(path, data.encode(encoding))
  494. def set_mode(self, bits, mask, files):
  495. if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):
  496. # Set the executable bits (owner, group, and world) on
  497. # all the files specified.
  498. for f in files:
  499. if self.dry_run:
  500. logger.info("changing mode of %s", f)
  501. else:
  502. mode = (os.stat(f).st_mode | bits) & mask
  503. logger.info("changing mode of %s to %o", f, mode)
  504. os.chmod(f, mode)
  505. set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)
  506. def ensure_dir(self, path):
  507. path = os.path.abspath(path)
  508. if path not in self.ensured and not os.path.exists(path):
  509. self.ensured.add(path)
  510. d, f = os.path.split(path)
  511. self.ensure_dir(d)
  512. logger.info('Creating %s' % path)
  513. if not self.dry_run:
  514. os.mkdir(path)
  515. if self.record:
  516. self.dirs_created.add(path)
  517. def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False):
  518. dpath = cache_from_source(path, not optimize)
  519. logger.info('Byte-compiling %s to %s', path, dpath)
  520. if not self.dry_run:
  521. if force or self.newer(path, dpath):
  522. if not prefix:
  523. diagpath = None
  524. else:
  525. assert path.startswith(prefix)
  526. diagpath = path[len(prefix):]
  527. compile_kwargs = {}
  528. if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'):
  529. compile_kwargs['invalidation_mode'] = py_compile.PycInvalidationMode.CHECKED_HASH
  530. py_compile.compile(path, dpath, diagpath, True, **compile_kwargs) # raise error
  531. self.record_as_written(dpath)
  532. return dpath
  533. def ensure_removed(self, path):
  534. if os.path.exists(path):
  535. if os.path.isdir(path) and not os.path.islink(path):
  536. logger.debug('Removing directory tree at %s', path)
  537. if not self.dry_run:
  538. shutil.rmtree(path)
  539. if self.record:
  540. if path in self.dirs_created:
  541. self.dirs_created.remove(path)
  542. else:
  543. if os.path.islink(path):
  544. s = 'link'
  545. else:
  546. s = 'file'
  547. logger.debug('Removing %s %s', s, path)
  548. if not self.dry_run:
  549. os.remove(path)
  550. if self.record:
  551. if path in self.files_written:
  552. self.files_written.remove(path)
  553. def is_writable(self, path):
  554. result = False
  555. while not result:
  556. if os.path.exists(path):
  557. result = os.access(path, os.W_OK)
  558. break
  559. parent = os.path.dirname(path)
  560. if parent == path:
  561. break
  562. path = parent
  563. return result
  564. def commit(self):
  565. """
  566. Commit recorded changes, turn off recording, return
  567. changes.
  568. """
  569. assert self.record
  570. result = self.files_written, self.dirs_created
  571. self._init_record()
  572. return result
  573. def rollback(self):
  574. if not self.dry_run:
  575. for f in list(self.files_written):
  576. if os.path.exists(f):
  577. os.remove(f)
  578. # dirs should all be empty now, except perhaps for
  579. # __pycache__ subdirs
  580. # reverse so that subdirs appear before their parents
  581. dirs = sorted(self.dirs_created, reverse=True)
  582. for d in dirs:
  583. flist = os.listdir(d)
  584. if flist:
  585. assert flist == ['__pycache__']
  586. sd = os.path.join(d, flist[0])
  587. os.rmdir(sd)
  588. os.rmdir(d) # should fail if non-empty
  589. self._init_record()
  590. def resolve(module_name, dotted_path):
  591. if module_name in sys.modules:
  592. mod = sys.modules[module_name]
  593. else:
  594. mod = __import__(module_name)
  595. if dotted_path is None:
  596. result = mod
  597. else:
  598. parts = dotted_path.split('.')
  599. result = getattr(mod, parts.pop(0))
  600. for p in parts:
  601. result = getattr(result, p)
  602. return result
  603. class ExportEntry(object):
  604. def __init__(self, name, prefix, suffix, flags):
  605. self.name = name
  606. self.prefix = prefix
  607. self.suffix = suffix
  608. self.flags = flags
  609. @cached_property
  610. def value(self):
  611. return resolve(self.prefix, self.suffix)
  612. def __repr__(self): # pragma: no cover
  613. return '<ExportEntry %s = %s:%s %s>' % (self.name, self.prefix,
  614. self.suffix, self.flags)
  615. def __eq__(self, other):
  616. if not isinstance(other, ExportEntry):
  617. result = False
  618. else:
  619. result = (self.name == other.name and
  620. self.prefix == other.prefix and
  621. self.suffix == other.suffix and
  622. self.flags == other.flags)
  623. return result
  624. __hash__ = object.__hash__
  625. ENTRY_RE = re.compile(r'''(?P<name>(\w|[-.+])+)
  626. \s*=\s*(?P<callable>(\w+)([:\.]\w+)*)
  627. \s*(\[\s*(?P<flags>\w+(=\w+)?(,\s*\w+(=\w+)?)*)\s*\])?
  628. ''', re.VERBOSE)
  629. def get_export_entry(specification):
  630. m = ENTRY_RE.search(specification)
  631. if not m:
  632. result = None
  633. if '[' in specification or ']' in specification:
  634. raise DistlibException("Invalid specification "
  635. "'%s'" % specification)
  636. else:
  637. d = m.groupdict()
  638. name = d['name']
  639. path = d['callable']
  640. colons = path.count(':')
  641. if colons == 0:
  642. prefix, suffix = path, None
  643. else:
  644. if colons != 1:
  645. raise DistlibException("Invalid specification "
  646. "'%s'" % specification)
  647. prefix, suffix = path.split(':')
  648. flags = d['flags']
  649. if flags is None:
  650. if '[' in specification or ']' in specification:
  651. raise DistlibException("Invalid specification "
  652. "'%s'" % specification)
  653. flags = []
  654. else:
  655. flags = [f.strip() for f in flags.split(',')]
  656. result = ExportEntry(name, prefix, suffix, flags)
  657. return result
  658. def get_cache_base(suffix=None):
  659. """
  660. Return the default base location for distlib caches. If the directory does
  661. not exist, it is created. Use the suffix provided for the base directory,
  662. and default to '.distlib' if it isn't provided.
  663. On Windows, if LOCALAPPDATA is defined in the environment, then it is
  664. assumed to be a directory, and will be the parent directory of the result.
  665. On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
  666. directory - using os.expanduser('~') - will be the parent directory of
  667. the result.
  668. The result is just the directory '.distlib' in the parent directory as
  669. determined above, or with the name specified with ``suffix``.
  670. """
  671. if suffix is None:
  672. suffix = '.distlib'
  673. if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
  674. result = os.path.expandvars('$localappdata')
  675. else:
  676. # Assume posix, or old Windows
  677. result = os.path.expanduser('~')
  678. # we use 'isdir' instead of 'exists', because we want to
  679. # fail if there's a file with that name
  680. if os.path.isdir(result):
  681. usable = os.access(result, os.W_OK)
  682. if not usable:
  683. logger.warning('Directory exists but is not writable: %s', result)
  684. else:
  685. try:
  686. os.makedirs(result)
  687. usable = True
  688. except OSError:
  689. logger.warning('Unable to create %s', result, exc_info=True)
  690. usable = False
  691. if not usable:
  692. result = tempfile.mkdtemp()
  693. logger.warning('Default location unusable, using %s', result)
  694. return os.path.join(result, suffix)
  695. def path_to_cache_dir(path):
  696. """
  697. Convert an absolute path to a directory name for use in a cache.
  698. The algorithm used is:
  699. #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
  700. #. Any occurrence of ``os.sep`` is replaced with ``'--'``.
  701. #. ``'.cache'`` is appended.
  702. """
  703. d, p = os.path.splitdrive(os.path.abspath(path))
  704. if d:
  705. d = d.replace(':', '---')
  706. p = p.replace(os.sep, '--')
  707. return d + p + '.cache'
  708. def ensure_slash(s):
  709. if not s.endswith('/'):
  710. return s + '/'
  711. return s
  712. def parse_credentials(netloc):
  713. username = password = None
  714. if '@' in netloc:
  715. prefix, netloc = netloc.split('@', 1)
  716. if ':' not in prefix:
  717. username = prefix
  718. else:
  719. username, password = prefix.split(':', 1)
  720. return username, password, netloc
  721. def get_process_umask():
  722. result = os.umask(0o22)
  723. os.umask(result)
  724. return result
  725. def is_string_sequence(seq):
  726. result = True
  727. i = None
  728. for i, s in enumerate(seq):
  729. if not isinstance(s, string_types):
  730. result = False
  731. break
  732. assert i is not None
  733. return result
  734. PROJECT_NAME_AND_VERSION = re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'
  735. '([a-z0-9_.+-]+)', re.I)
  736. PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')
  737. def split_filename(filename, project_name=None):
  738. """
  739. Extract name, version, python version from a filename (no extension)
  740. Return name, version, pyver or None
  741. """
  742. result = None
  743. pyver = None
  744. filename = unquote(filename).replace(' ', '-')
  745. m = PYTHON_VERSION.search(filename)
  746. if m:
  747. pyver = m.group(1)
  748. filename = filename[:m.start()]
  749. if project_name and len(filename) > len(project_name) + 1:
  750. m = re.match(re.escape(project_name) + r'\b', filename)
  751. if m:
  752. n = m.end()
  753. result = filename[:n], filename[n + 1:], pyver
  754. if result is None:
  755. m = PROJECT_NAME_AND_VERSION.match(filename)
  756. if m:
  757. result = m.group(1), m.group(3), pyver
  758. return result
  759. # Allow spaces in name because of legacy dists like "Twisted Core"
  760. NAME_VERSION_RE = re.compile(r'(?P<name>[\w .-]+)\s*'
  761. r'\(\s*(?P<ver>[^\s)]+)\)$')
  762. def parse_name_and_version(p):
  763. """
  764. A utility method used to get name and version from a string.
  765. From e.g. a Provides-Dist value.
  766. :param p: A value in a form 'foo (1.0)'
  767. :return: The name and version as a tuple.
  768. """
  769. m = NAME_VERSION_RE.match(p)
  770. if not m:
  771. raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
  772. d = m.groupdict()
  773. return d['name'].strip().lower(), d['ver']
  774. def get_extras(requested, available):
  775. result = set()
  776. requested = set(requested or [])
  777. available = set(available or [])
  778. if '*' in requested:
  779. requested.remove('*')
  780. result |= available
  781. for r in requested:
  782. if r == '-':
  783. result.add(r)
  784. elif r.startswith('-'):
  785. unwanted = r[1:]
  786. if unwanted not in available:
  787. logger.warning('undeclared extra: %s' % unwanted)
  788. if unwanted in result:
  789. result.remove(unwanted)
  790. else:
  791. if r not in available:
  792. logger.warning('undeclared extra: %s' % r)
  793. result.add(r)
  794. return result
  795. #
  796. # Extended metadata functionality
  797. #
  798. def _get_external_data(url):
  799. result = {}
  800. try:
  801. # urlopen might fail if it runs into redirections,
  802. # because of Python issue #13696. Fixed in locators
  803. # using a custom redirect handler.
  804. resp = urlopen(url)
  805. headers = resp.info()
  806. ct = headers.get('Content-Type')
  807. if not ct.startswith('application/json'):
  808. logger.debug('Unexpected response for JSON request: %s', ct)
  809. else:
  810. reader = codecs.getreader('utf-8')(resp)
  811. #data = reader.read().decode('utf-8')
  812. #result = json.loads(data)
  813. result = json.load(reader)
  814. except Exception as e:
  815. logger.exception('Failed to get external data for %s: %s', url, e)
  816. return result
  817. _external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
  818. def get_project_data(name):
  819. url = '%s/%s/project.json' % (name[0].upper(), name)
  820. url = urljoin(_external_data_base_url, url)
  821. result = _get_external_data(url)
  822. return result
  823. def get_package_data(name, version):
  824. url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)
  825. url = urljoin(_external_data_base_url, url)
  826. return _get_external_data(url)
  827. class Cache(object):
  828. """
  829. A class implementing a cache for resources that need to live in the file system
  830. e.g. shared libraries. This class was moved from resources to here because it
  831. could be used by other modules, e.g. the wheel module.
  832. """
  833. def __init__(self, base):
  834. """
  835. Initialise an instance.
  836. :param base: The base directory where the cache should be located.
  837. """
  838. # we use 'isdir' instead of 'exists', because we want to
  839. # fail if there's a file with that name
  840. if not os.path.isdir(base): # pragma: no cover
  841. os.makedirs(base)
  842. if (os.stat(base).st_mode & 0o77) != 0:
  843. logger.warning('Directory \'%s\' is not private', base)
  844. self.base = os.path.abspath(os.path.normpath(base))
  845. def prefix_to_dir(self, prefix):
  846. """
  847. Converts a resource prefix to a directory name in the cache.
  848. """
  849. return path_to_cache_dir(prefix)
  850. def clear(self):
  851. """
  852. Clear the cache.
  853. """
  854. not_removed = []
  855. for fn in os.listdir(self.base):
  856. fn = os.path.join(self.base, fn)
  857. try:
  858. if os.path.islink(fn) or os.path.isfile(fn):
  859. os.remove(fn)
  860. elif os.path.isdir(fn):
  861. shutil.rmtree(fn)
  862. except Exception:
  863. not_removed.append(fn)
  864. return not_removed
  865. class EventMixin(object):
  866. """
  867. A very simple publish/subscribe system.
  868. """
  869. def __init__(self):
  870. self._subscribers = {}
  871. def add(self, event, subscriber, append=True):
  872. """
  873. Add a subscriber for an event.
  874. :param event: The name of an event.
  875. :param subscriber: The subscriber to be added (and called when the
  876. event is published).
  877. :param append: Whether to append or prepend the subscriber to an
  878. existing subscriber list for the event.
  879. """
  880. subs = self._subscribers
  881. if event not in subs:
  882. subs[event] = deque([subscriber])
  883. else:
  884. sq = subs[event]
  885. if append:
  886. sq.append(subscriber)
  887. else:
  888. sq.appendleft(subscriber)
  889. def remove(self, event, subscriber):
  890. """
  891. Remove a subscriber for an event.
  892. :param event: The name of an event.
  893. :param subscriber: The subscriber to be removed.
  894. """
  895. subs = self._subscribers
  896. if event not in subs:
  897. raise ValueError('No subscribers: %r' % event)
  898. subs[event].remove(subscriber)
  899. def get_subscribers(self, event):
  900. """
  901. Return an iterator for the subscribers for an event.
  902. :param event: The event to return subscribers for.
  903. """
  904. return iter(self._subscribers.get(event, ()))
  905. def publish(self, event, *args, **kwargs):
  906. """
  907. Publish a event and return a list of values returned by its
  908. subscribers.
  909. :param event: The event to publish.
  910. :param args: The positional arguments to pass to the event's
  911. subscribers.
  912. :param kwargs: The keyword arguments to pass to the event's
  913. subscribers.
  914. """
  915. result = []
  916. for subscriber in self.get_subscribers(event):
  917. try:
  918. value = subscriber(event, *args, **kwargs)
  919. except Exception:
  920. logger.exception('Exception during event publication')
  921. value = None
  922. result.append(value)
  923. logger.debug('publish %s: args = %s, kwargs = %s, result = %s',
  924. event, args, kwargs, result)
  925. return result
  926. #
  927. # Simple sequencing
  928. #
  929. class Sequencer(object):
  930. def __init__(self):
  931. self._preds = {}
  932. self._succs = {}
  933. self._nodes = set() # nodes with no preds/succs
  934. def add_node(self, node):
  935. self._nodes.add(node)
  936. def remove_node(self, node, edges=False):
  937. if node in self._nodes:
  938. self._nodes.remove(node)
  939. if edges:
  940. for p in set(self._preds.get(node, ())):
  941. self.remove(p, node)
  942. for s in set(self._succs.get(node, ())):
  943. self.remove(node, s)
  944. # Remove empties
  945. for k, v in list(self._preds.items()):
  946. if not v:
  947. del self._preds[k]
  948. for k, v in list(self._succs.items()):
  949. if not v:
  950. del self._succs[k]
  951. def add(self, pred, succ):
  952. assert pred != succ
  953. self._preds.setdefault(succ, set()).add(pred)
  954. self._succs.setdefault(pred, set()).add(succ)
  955. def remove(self, pred, succ):
  956. assert pred != succ
  957. try:
  958. preds = self._preds[succ]
  959. succs = self._succs[pred]
  960. except KeyError: # pragma: no cover
  961. raise ValueError('%r not a successor of anything' % succ)
  962. try:
  963. preds.remove(pred)
  964. succs.remove(succ)
  965. except KeyError: # pragma: no cover
  966. raise ValueError('%r not a successor of %r' % (succ, pred))
  967. def is_step(self, step):
  968. return (step in self._preds or step in self._succs or
  969. step in self._nodes)
  970. def get_steps(self, final):
  971. if not self.is_step(final):
  972. raise ValueError('Unknown: %r' % final)
  973. result = []
  974. todo = []
  975. seen = set()
  976. todo.append(final)
  977. while todo:
  978. step = todo.pop(0)
  979. if step in seen:
  980. # if a step was already seen,
  981. # move it to the end (so it will appear earlier
  982. # when reversed on return) ... but not for the
  983. # final step, as that would be confusing for
  984. # users
  985. if step != final:
  986. result.remove(step)
  987. result.append(step)
  988. else:
  989. seen.add(step)
  990. result.append(step)
  991. preds = self._preds.get(step, ())
  992. todo.extend(preds)
  993. return reversed(result)
  994. @property
  995. def strong_connections(self):
  996. #http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  997. index_counter = [0]
  998. stack = []
  999. lowlinks = {}
  1000. index = {}
  1001. result = []
  1002. graph = self._succs
  1003. def strongconnect(node):
  1004. # set the depth index for this node to the smallest unused index
  1005. index[node] = index_counter[0]
  1006. lowlinks[node] = index_counter[0]
  1007. index_counter[0] += 1
  1008. stack.append(node)
  1009. # Consider successors
  1010. try:
  1011. successors = graph[node]
  1012. except Exception:
  1013. successors = []
  1014. for successor in successors:
  1015. if successor not in lowlinks:
  1016. # Successor has not yet been visited
  1017. strongconnect(successor)
  1018. lowlinks[node] = min(lowlinks[node],lowlinks[successor])
  1019. elif successor in stack:
  1020. # the successor is in the stack and hence in the current
  1021. # strongly connected component (SCC)
  1022. lowlinks[node] = min(lowlinks[node],index[successor])
  1023. # If `node` is a root node, pop the stack and generate an SCC
  1024. if lowlinks[node] == index[node]:
  1025. connected_component = []
  1026. while True:
  1027. successor = stack.pop()
  1028. connected_component.append(successor)
  1029. if successor == node: break
  1030. component = tuple(connected_component)
  1031. # storing the result
  1032. result.append(component)
  1033. for node in graph:
  1034. if node not in lowlinks:
  1035. strongconnect(node)
  1036. return result
  1037. @property
  1038. def dot(self):
  1039. result = ['digraph G {']
  1040. for succ in self._preds:
  1041. preds = self._preds[succ]
  1042. for pred in preds:
  1043. result.append(' %s -> %s;' % (pred, succ))
  1044. for node in self._nodes:
  1045. result.append(' %s;' % node)
  1046. result.append('}')
  1047. return '\n'.join(result)
  1048. #
  1049. # Unarchiving functionality for zip, tar, tgz, tbz, whl
  1050. #
  1051. ARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip',
  1052. '.tgz', '.tbz', '.whl')
  1053. def unarchive(archive_filename, dest_dir, format=None, check=True):
  1054. def check_path(path):
  1055. if not isinstance(path, text_type):
  1056. path = path.decode('utf-8')
  1057. p = os.path.abspath(os.path.join(dest_dir, path))
  1058. if not p.startswith(dest_dir) or p[plen] != os.sep:
  1059. raise ValueError('path outside destination: %r' % p)
  1060. dest_dir = os.path.abspath(dest_dir)
  1061. plen = len(dest_dir)
  1062. archive = None
  1063. if format is None:
  1064. if archive_filename.endswith(('.zip', '.whl')):
  1065. format = 'zip'
  1066. elif archive_filename.endswith(('.tar.gz', '.tgz')):
  1067. format = 'tgz'
  1068. mode = 'r:gz'
  1069. elif archive_filename.endswith(('.tar.bz2', '.tbz')):
  1070. format = 'tbz'
  1071. mode = 'r:bz2'
  1072. elif archive_filename.endswith('.tar'):
  1073. format = 'tar'
  1074. mode = 'r'
  1075. else: # pragma: no cover
  1076. raise ValueError('Unknown format for %r' % archive_filename)
  1077. try:
  1078. if format == 'zip':
  1079. archive = ZipFile(archive_filename, 'r')
  1080. if check:
  1081. names = archive.namelist()
  1082. for name in names:
  1083. check_path(name)
  1084. else:
  1085. archive = tarfile.open(archive_filename, mode)
  1086. if check:
  1087. names = archive.getnames()
  1088. for name in names:
  1089. check_path(name)
  1090. if format != 'zip' and sys.version_info[0] < 3:
  1091. # See Python issue 17153. If the dest path contains Unicode,
  1092. # tarfile extraction fails on Python 2.x if a member path name
  1093. # contains non-ASCII characters - it leads to an implicit
  1094. # bytes -> unicode conversion using ASCII to decode.
  1095. for tarinfo in archive.getmembers():
  1096. if not isinstance(tarinfo.name, text_type):
  1097. tarinfo.name = tarinfo.name.decode('utf-8')
  1098. archive.extractall(dest_dir)
  1099. finally:
  1100. if archive:
  1101. archive.close()
  1102. def zip_dir(directory):
  1103. """zip a directory tree into a BytesIO object"""
  1104. result = io.BytesIO()
  1105. dlen = len(directory)
  1106. with ZipFile(result, "w") as zf:
  1107. for root, dirs, files in os.walk(directory):
  1108. for name in files:
  1109. full = os.path.join(root, name)
  1110. rel = root[dlen:]
  1111. dest = os.path.join(rel, name)
  1112. zf.write(full, dest)
  1113. return result
  1114. #
  1115. # Simple progress bar
  1116. #
  1117. UNITS = ('', 'K', 'M', 'G','T','P')
  1118. class Progress(object):
  1119. unknown = 'UNKNOWN'
  1120. def __init__(self, minval=0, maxval=100):
  1121. assert maxval is None or maxval >= minval
  1122. self.min = self.cur = minval
  1123. self.max = maxval
  1124. self.started = None
  1125. self.elapsed = 0
  1126. self.done = False
  1127. def update(self, curval):
  1128. assert self.min <= curval
  1129. assert self.max is None or curval <= self.max
  1130. self.cur = curval
  1131. now = time.time()
  1132. if self.started is None:
  1133. self.started = now
  1134. else:
  1135. self.elapsed = now - self.started
  1136. def increment(self, incr):
  1137. assert incr >= 0
  1138. self.update(self.cur + incr)
  1139. def start(self):
  1140. self.update(self.min)
  1141. return self
  1142. def stop(self):
  1143. if self.max is not None:
  1144. self.update(self.max)
  1145. self.done = True
  1146. @property
  1147. def maximum(self):
  1148. return self.unknown if self.max is None else self.max
  1149. @property
  1150. def percentage(self):
  1151. if self.done:
  1152. result = '100 %'
  1153. elif self.max is None:
  1154. result = ' ?? %'
  1155. else:
  1156. v = 100.0 * (self.cur - self.min) / (self.max - self.min)
  1157. result = '%3d %%' % v
  1158. return result
  1159. def format_duration(self, duration):
  1160. if (duration <= 0) and self.max is None or self.cur == self.min:
  1161. result = '??:??:??'
  1162. #elif duration < 1:
  1163. # result = '--:--:--'
  1164. else:
  1165. result = time.strftime('%H:%M:%S', time.gmtime(duration))
  1166. return result
  1167. @property
  1168. def ETA(self):
  1169. if self.done:
  1170. prefix = 'Done'
  1171. t = self.elapsed
  1172. #import pdb; pdb.set_trace()
  1173. else:
  1174. prefix = 'ETA '
  1175. if self.max is None:
  1176. t = -1
  1177. elif self.elapsed == 0 or (self.cur == self.min):
  1178. t = 0
  1179. else:
  1180. #import pdb; pdb.set_trace()
  1181. t = float(self.max - self.min)
  1182. t /= self.cur - self.min
  1183. t = (t - 1) * self.elapsed
  1184. return '%s: %s' % (prefix, self.format_duration(t))
  1185. @property
  1186. def speed(self):
  1187. if self.elapsed == 0:
  1188. result = 0.0
  1189. else:
  1190. result = (self.cur - self.min) / self.elapsed
  1191. for unit in UNITS:
  1192. if result < 1000:
  1193. break
  1194. result /= 1000.0
  1195. return '%d %sB/s' % (result, unit)
  1196. #
  1197. # Glob functionality
  1198. #
  1199. RICH_GLOB = re.compile(r'\{([^}]*)\}')
  1200. _CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
  1201. _CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
  1202. def iglob(path_glob):
  1203. """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
  1204. if _CHECK_RECURSIVE_GLOB.search(path_glob):
  1205. msg = """invalid glob %r: recursive glob "**" must be used alone"""
  1206. raise ValueError(msg % path_glob)
  1207. if _CHECK_MISMATCH_SET.search(path_glob):
  1208. msg = """invalid glob %r: mismatching set marker '{' or '}'"""
  1209. raise ValueError(msg % path_glob)
  1210. return _iglob(path_glob)
  1211. def _iglob(path_glob):
  1212. rich_path_glob = RICH_GLOB.split(path_glob, 1)
  1213. if len(rich_path_glob) > 1:
  1214. assert len(rich_path_glob) == 3, rich_path_glob
  1215. prefix, set, suffix = rich_path_glob
  1216. for item in set.split(','):
  1217. for path in _iglob(''.join((prefix, item, suffix))):
  1218. yield path
  1219. else:
  1220. if '**' not in path_glob:
  1221. for item in std_iglob(path_glob):
  1222. yield item
  1223. else:
  1224. prefix, radical = path_glob.split('**', 1)
  1225. if prefix == '':
  1226. prefix = '.'
  1227. if radical == '':
  1228. radical = '*'
  1229. else:
  1230. # we support both
  1231. radical = radical.lstrip('/')
  1232. radical = radical.lstrip('\\')
  1233. for path, dir, files in os.walk(prefix):
  1234. path = os.path.normpath(path)
  1235. for fn in _iglob(os.path.join(path, radical)):
  1236. yield fn
  1237. if ssl:
  1238. from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname,
  1239. CertificateError)
  1240. #
  1241. # HTTPSConnection which verifies certificates/matches domains
  1242. #
  1243. class HTTPSConnection(httplib.HTTPSConnection):
  1244. ca_certs = None # set this to the path to the certs file (.pem)
  1245. check_domain = True # only used if ca_certs is not None
  1246. # noinspection PyPropertyAccess
  1247. def connect(self):
  1248. sock = socket.create_connection((self.host, self.port), self.timeout)
  1249. if getattr(self, '_tunnel_host', False):
  1250. self.sock = sock
  1251. self._tunnel()
  1252. if not hasattr(ssl, 'SSLContext'):
  1253. # For 2.x
  1254. if self.ca_certs:
  1255. cert_reqs = ssl.CERT_REQUIRED
  1256. else:
  1257. cert_reqs = ssl.CERT_NONE
  1258. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
  1259. cert_reqs=cert_reqs,
  1260. ssl_version=ssl.PROTOCOL_SSLv23,
  1261. ca_certs=self.ca_certs)
  1262. else: # pragma: no cover
  1263. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  1264. context.options |= ssl.OP_NO_SSLv2
  1265. if self.cert_file:
  1266. context.load_cert_chain(self.cert_file, self.key_file)
  1267. kwargs = {}
  1268. if self.ca_certs:
  1269. context.verify_mode = ssl.CERT_REQUIRED
  1270. context.load_verify_locations(cafile=self.ca_certs)
  1271. if getattr(ssl, 'HAS_SNI', False):
  1272. kwargs['server_hostname'] = self.host
  1273. self.sock = context.wrap_socket(sock, **kwargs)
  1274. if self.ca_certs and self.check_domain:
  1275. try:
  1276. match_hostname(self.sock.getpeercert(), self.host)
  1277. logger.debug('Host verified: %s', self.host)
  1278. except CertificateError: # pragma: no cover
  1279. self.sock.shutdown(socket.SHUT_RDWR)
  1280. self.sock.close()
  1281. raise
  1282. class HTTPSHandler(BaseHTTPSHandler):
  1283. def __init__(self, ca_certs, check_domain=True):
  1284. BaseHTTPSHandler.__init__(self)
  1285. self.ca_certs = ca_certs
  1286. self.check_domain = check_domain
  1287. def _conn_maker(self, *args, **kwargs):
  1288. """
  1289. This is called to create a connection instance. Normally you'd
  1290. pass a connection class to do_open, but it doesn't actually check for
  1291. a class, and just expects a callable. As long as we behave just as a
  1292. constructor would have, we should be OK. If it ever changes so that
  1293. we *must* pass a class, we'll create an UnsafeHTTPSConnection class
  1294. which just sets check_domain to False in the class definition, and
  1295. choose which one to pass to do_open.
  1296. """
  1297. result = HTTPSConnection(*args, **kwargs)
  1298. if self.ca_certs:
  1299. result.ca_certs = self.ca_certs
  1300. result.check_domain = self.check_domain
  1301. return result
  1302. def https_open(self, req):
  1303. try:
  1304. return self.do_open(self._conn_maker, req)
  1305. except URLError as e:
  1306. if 'certificate verify failed' in str(e.reason):
  1307. raise CertificateError('Unable to verify server certificate '
  1308. 'for %s' % req.host)
  1309. else:
  1310. raise
  1311. #
  1312. # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-
  1313. # Middle proxy using HTTP listens on port 443, or an index mistakenly serves
  1314. # HTML containing a http://xyz link when it should be https://xyz),
  1315. # you can use the following handler class, which does not allow HTTP traffic.
  1316. #
  1317. # It works by inheriting from HTTPHandler - so build_opener won't add a
  1318. # handler for HTTP itself.
  1319. #
  1320. class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):
  1321. def http_open(self, req):
  1322. raise URLError('Unexpected HTTP request on what should be a secure '
  1323. 'connection: %s' % req)
  1324. #
  1325. # XML-RPC with timeouts
  1326. #
  1327. _ver_info = sys.version_info[:2]
  1328. if _ver_info == (2, 6):
  1329. class HTTP(httplib.HTTP):
  1330. def __init__(self, host='', port=None, **kwargs):
  1331. if port == 0: # 0 means use port 0, not the default port
  1332. port = None
  1333. self._setup(self._connection_class(host, port, **kwargs))
  1334. if ssl:
  1335. class HTTPS(httplib.HTTPS):
  1336. def __init__(self, host='', port=None, **kwargs):
  1337. if port == 0: # 0 means use port 0, not the default port
  1338. port = None
  1339. self._setup(self._connection_class(host, port, **kwargs))
  1340. class Transport(xmlrpclib.Transport):
  1341. def __init__(self, timeout, use_datetime=0):
  1342. self.timeout = timeout
  1343. xmlrpclib.Transport.__init__(self, use_datetime)
  1344. def make_connection(self, host):
  1345. h, eh, x509 = self.get_host_info(host)
  1346. if _ver_info == (2, 6):
  1347. result = HTTP(h, timeout=self.timeout)
  1348. else:
  1349. if not self._connection or host != self._connection[0]:
  1350. self._extra_headers = eh
  1351. self._connection = host, httplib.HTTPConnection(h)
  1352. result = self._connection[1]
  1353. return result
  1354. if ssl:
  1355. class SafeTransport(xmlrpclib.SafeTransport):
  1356. def __init__(self, timeout, use_datetime=0):
  1357. self.timeout = timeout
  1358. xmlrpclib.SafeTransport.__init__(self, use_datetime)
  1359. def make_connection(self, host):
  1360. h, eh, kwargs = self.get_host_info(host)
  1361. if not kwargs:
  1362. kwargs = {}
  1363. kwargs['timeout'] = self.timeout
  1364. if _ver_info == (2, 6):
  1365. result = HTTPS(host, None, **kwargs)
  1366. else:
  1367. if not self._connection or host != self._connection[0]:
  1368. self._extra_headers = eh
  1369. self._connection = host, httplib.HTTPSConnection(h, None,
  1370. **kwargs)
  1371. result = self._connection[1]
  1372. return result
  1373. class ServerProxy(xmlrpclib.ServerProxy):
  1374. def __init__(self, uri, **kwargs):
  1375. self.timeout = timeout = kwargs.pop('timeout', None)
  1376. # The above classes only come into play if a timeout
  1377. # is specified
  1378. if timeout is not None:
  1379. scheme, _ = splittype(uri)
  1380. use_datetime = kwargs.get('use_datetime', 0)
  1381. if scheme == 'https':
  1382. tcls = SafeTransport
  1383. else:
  1384. tcls = Transport
  1385. kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)
  1386. self.transport = t
  1387. xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)
  1388. #
  1389. # CSV functionality. This is provided because on 2.x, the csv module can't
  1390. # handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.
  1391. #
  1392. def _csv_open(fn, mode, **kwargs):
  1393. if sys.version_info[0] < 3:
  1394. mode += 'b'
  1395. else:
  1396. kwargs['newline'] = ''
  1397. # Python 3 determines encoding from locale. Force 'utf-8'
  1398. # file encoding to match other forced utf-8 encoding
  1399. kwargs['encoding'] = 'utf-8'
  1400. return open(fn, mode, **kwargs)
  1401. class CSVBase(object):
  1402. defaults = {
  1403. 'delimiter': str(','), # The strs are used because we need native
  1404. 'quotechar': str('"'), # str in the csv API (2.x won't take
  1405. 'lineterminator': str('\n') # Unicode)
  1406. }
  1407. def __enter__(self):
  1408. return self
  1409. def __exit__(self, *exc_info):
  1410. self.stream.close()
  1411. class CSVReader(CSVBase):
  1412. def __init__(self, **kwargs):
  1413. if 'stream' in kwargs:
  1414. stream = kwargs['stream']
  1415. if sys.version_info[0] >= 3:
  1416. # needs to be a text stream
  1417. stream = codecs.getreader('utf-8')(stream)
  1418. self.stream = stream
  1419. else:
  1420. self.stream = _csv_open(kwargs['path'], 'r')
  1421. self.reader = csv.reader(self.stream, **self.defaults)
  1422. def __iter__(self):
  1423. return self
  1424. def next(self):
  1425. result = next(self.reader)
  1426. if sys.version_info[0] < 3:
  1427. for i, item in enumerate(result):
  1428. if not isinstance(item, text_type):
  1429. result[i] = item.decode('utf-8')
  1430. return result
  1431. __next__ = next
  1432. class CSVWriter(CSVBase):
  1433. def __init__(self, fn, **kwargs):
  1434. self.stream = _csv_open(fn, 'w')
  1435. self.writer = csv.writer(self.stream, **self.defaults)
  1436. def writerow(self, row):
  1437. if sys.version_info[0] < 3:
  1438. r = []
  1439. for item in row:
  1440. if isinstance(item, text_type):
  1441. item = item.encode('utf-8')
  1442. r.append(item)
  1443. row = r
  1444. self.writer.writerow(row)
  1445. #
  1446. # Configurator functionality
  1447. #
  1448. class Configurator(BaseConfigurator):
  1449. value_converters = dict(BaseConfigurator.value_converters)
  1450. value_converters['inc'] = 'inc_convert'
  1451. def __init__(self, config, base=None):
  1452. super(Configurator, self).__init__(config)
  1453. self.base = base or os.getcwd()
  1454. def configure_custom(self, config):
  1455. def convert(o):
  1456. if isinstance(o, (list, tuple)):
  1457. result = type(o)([convert(i) for i in o])
  1458. elif isinstance(o, dict):
  1459. if '()' in o:
  1460. result = self.configure_custom(o)
  1461. else:
  1462. result = {}
  1463. for k in o:
  1464. result[k] = convert(o[k])
  1465. else:
  1466. result = self.convert(o)
  1467. return result
  1468. c = config.pop('()')
  1469. if not callable(c):
  1470. c = self.resolve(c)
  1471. props = config.pop('.', None)
  1472. # Check for valid identifiers
  1473. args = config.pop('[]', ())
  1474. if args:
  1475. args = tuple([convert(o) for o in args])
  1476. items = [(k, convert(config[k])) for k in config if valid_ident(k)]
  1477. kwargs = dict(items)
  1478. result = c(*args, **kwargs)
  1479. if props:
  1480. for n, v in props.items():
  1481. setattr(result, n, convert(v))
  1482. return result
  1483. def __getitem__(self, key):
  1484. result = self.config[key]
  1485. if isinstance(result, dict) and '()' in result:
  1486. self.config[key] = result = self.configure_custom(result)
  1487. return result
  1488. def inc_convert(self, value):
  1489. """Default converter for the inc:// protocol."""
  1490. if not os.path.isabs(value):
  1491. value = os.path.join(self.base, value)
  1492. with codecs.open(value, 'r', encoding='utf-8') as f:
  1493. result = json.load(f)
  1494. return result
  1495. class SubprocessMixin(object):
  1496. """
  1497. Mixin for running subprocesses and capturing their output
  1498. """
  1499. def __init__(self, verbose=False, progress=None):
  1500. self.verbose = verbose
  1501. self.progress = progress
  1502. def reader(self, stream, context):
  1503. """
  1504. Read lines from a subprocess' output stream and either pass to a progress
  1505. callable (if specified) or write progress information to sys.stderr.
  1506. """
  1507. progress = self.progress
  1508. verbose = self.verbose
  1509. while True:
  1510. s = stream.readline()
  1511. if not s:
  1512. break
  1513. if progress is not None:
  1514. progress(s, context)
  1515. else:
  1516. if not verbose:
  1517. sys.stderr.write('.')
  1518. else:
  1519. sys.stderr.write(s.decode('utf-8'))
  1520. sys.stderr.flush()
  1521. stream.close()
  1522. def run_command(self, cmd, **kwargs):
  1523. p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  1524. stderr=subprocess.PIPE, **kwargs)
  1525. t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
  1526. t1.start()
  1527. t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))
  1528. t2.start()
  1529. p.wait()
  1530. t1.join()
  1531. t2.join()
  1532. if self.progress is not None:
  1533. self.progress('done.', 'main')
  1534. elif self.verbose:
  1535. sys.stderr.write('done.\n')
  1536. return p
  1537. def normalize_name(name):
  1538. """Normalize a python package name a la PEP 503"""
  1539. # https://www.python.org/dev/peps/pep-0503/#normalized-names
  1540. return re.sub('[-_.]+', '-', name).lower()