PageRenderTime 214ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/pip/_vendor/distlib/util.py

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