progress_bars.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. from __future__ import division
  2. import itertools
  3. import sys
  4. from signal import SIGINT, default_int_handler, signal
  5. from pip._vendor import six
  6. from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
  7. from pip._vendor.progress.spinner import Spinner
  8. from pip._internal.utils.compat import WINDOWS
  9. from pip._internal.utils.logging import get_indentation
  10. from pip._internal.utils.misc import format_size
  11. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  12. if MYPY_CHECK_RUNNING:
  13. from typing import Any, Dict, List
  14. try:
  15. from pip._vendor import colorama
  16. # Lots of different errors can come from this, including SystemError and
  17. # ImportError.
  18. except Exception:
  19. colorama = None
  20. def _select_progress_class(preferred, fallback):
  21. # type: (Bar, Bar) -> Bar
  22. encoding = getattr(preferred.file, "encoding", None)
  23. # If we don't know what encoding this file is in, then we'll just assume
  24. # that it doesn't support unicode and use the ASCII bar.
  25. if not encoding:
  26. return fallback
  27. # Collect all of the possible characters we want to use with the preferred
  28. # bar.
  29. characters = [
  30. getattr(preferred, "empty_fill", six.text_type()),
  31. getattr(preferred, "fill", six.text_type()),
  32. ]
  33. characters += list(getattr(preferred, "phases", []))
  34. # Try to decode the characters we're using for the bar using the encoding
  35. # of the given file, if this works then we'll assume that we can use the
  36. # fancier bar and if not we'll fall back to the plaintext bar.
  37. try:
  38. six.text_type().join(characters).encode(encoding)
  39. except UnicodeEncodeError:
  40. return fallback
  41. else:
  42. return preferred
  43. _BaseBar = _select_progress_class(IncrementalBar, Bar) # type: Any
  44. class InterruptibleMixin(object):
  45. """
  46. Helper to ensure that self.finish() gets called on keyboard interrupt.
  47. This allows downloads to be interrupted without leaving temporary state
  48. (like hidden cursors) behind.
  49. This class is similar to the progress library's existing SigIntMixin
  50. helper, but as of version 1.2, that helper has the following problems:
  51. 1. It calls sys.exit().
  52. 2. It discards the existing SIGINT handler completely.
  53. 3. It leaves its own handler in place even after an uninterrupted finish,
  54. which will have unexpected delayed effects if the user triggers an
  55. unrelated keyboard interrupt some time after a progress-displaying
  56. download has already completed, for example.
  57. """
  58. def __init__(self, *args, **kwargs):
  59. # type: (List[Any], Dict[Any, Any]) -> None
  60. """
  61. Save the original SIGINT handler for later.
  62. """
  63. super(InterruptibleMixin, self).__init__( # type: ignore
  64. *args,
  65. **kwargs
  66. )
  67. self.original_handler = signal(SIGINT, self.handle_sigint)
  68. # If signal() returns None, the previous handler was not installed from
  69. # Python, and we cannot restore it. This probably should not happen,
  70. # but if it does, we must restore something sensible instead, at least.
  71. # The least bad option should be Python's default SIGINT handler, which
  72. # just raises KeyboardInterrupt.
  73. if self.original_handler is None:
  74. self.original_handler = default_int_handler
  75. def finish(self):
  76. # type: () -> None
  77. """
  78. Restore the original SIGINT handler after finishing.
  79. This should happen regardless of whether the progress display finishes
  80. normally, or gets interrupted.
  81. """
  82. super(InterruptibleMixin, self).finish() # type: ignore
  83. signal(SIGINT, self.original_handler)
  84. def handle_sigint(self, signum, frame): # type: ignore
  85. """
  86. Call self.finish() before delegating to the original SIGINT handler.
  87. This handler should only be in place while the progress display is
  88. active.
  89. """
  90. self.finish()
  91. self.original_handler(signum, frame)
  92. class SilentBar(Bar):
  93. def update(self):
  94. # type: () -> None
  95. pass
  96. class BlueEmojiBar(IncrementalBar):
  97. suffix = "%(percent)d%%"
  98. bar_prefix = " "
  99. bar_suffix = " "
  100. phases = (u"\U0001F539", u"\U0001F537", u"\U0001F535") # type: Any
  101. class DownloadProgressMixin(object):
  102. def __init__(self, *args, **kwargs):
  103. # type: (List[Any], Dict[Any, Any]) -> None
  104. super(DownloadProgressMixin, self).__init__( # type: ignore
  105. *args,
  106. **kwargs
  107. )
  108. self.message = (" " * (
  109. get_indentation() + 2
  110. )) + self.message # type: str
  111. @property
  112. def downloaded(self):
  113. # type: () -> str
  114. return format_size(self.index) # type: ignore
  115. @property
  116. def download_speed(self):
  117. # type: () -> str
  118. # Avoid zero division errors...
  119. if self.avg == 0.0: # type: ignore
  120. return "..."
  121. return format_size(1 / self.avg) + "/s" # type: ignore
  122. @property
  123. def pretty_eta(self):
  124. # type: () -> str
  125. if self.eta: # type: ignore
  126. return "eta {}".format(self.eta_td) # type: ignore
  127. return ""
  128. def iter(self, it): # type: ignore
  129. for x in it:
  130. yield x
  131. self.next(len(x))
  132. self.finish()
  133. class WindowsMixin(object):
  134. def __init__(self, *args, **kwargs):
  135. # type: (List[Any], Dict[Any, Any]) -> None
  136. # The Windows terminal does not support the hide/show cursor ANSI codes
  137. # even with colorama. So we'll ensure that hide_cursor is False on
  138. # Windows.
  139. # This call needs to go before the super() call, so that hide_cursor
  140. # is set in time. The base progress bar class writes the "hide cursor"
  141. # code to the terminal in its init, so if we don't set this soon
  142. # enough, we get a "hide" with no corresponding "show"...
  143. if WINDOWS and self.hide_cursor: # type: ignore
  144. self.hide_cursor = False
  145. super(WindowsMixin, self).__init__(*args, **kwargs) # type: ignore
  146. # Check if we are running on Windows and we have the colorama module,
  147. # if we do then wrap our file with it.
  148. if WINDOWS and colorama:
  149. self.file = colorama.AnsiToWin32(self.file) # type: ignore
  150. # The progress code expects to be able to call self.file.isatty()
  151. # but the colorama.AnsiToWin32() object doesn't have that, so we'll
  152. # add it.
  153. self.file.isatty = lambda: self.file.wrapped.isatty()
  154. # The progress code expects to be able to call self.file.flush()
  155. # but the colorama.AnsiToWin32() object doesn't have that, so we'll
  156. # add it.
  157. self.file.flush = lambda: self.file.wrapped.flush()
  158. class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin,
  159. DownloadProgressMixin):
  160. file = sys.stdout
  161. message = "%(percent)d%%"
  162. suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s"
  163. # NOTE: The "type: ignore" comments on the following classes are there to
  164. # work around https://github.com/python/typing/issues/241
  165. class DefaultDownloadProgressBar(BaseDownloadProgressBar,
  166. _BaseBar):
  167. pass
  168. class DownloadSilentBar(BaseDownloadProgressBar, SilentBar): # type: ignore
  169. pass
  170. class DownloadBar(BaseDownloadProgressBar, # type: ignore
  171. Bar):
  172. pass
  173. class DownloadFillingCirclesBar(BaseDownloadProgressBar, # type: ignore
  174. FillingCirclesBar):
  175. pass
  176. class DownloadBlueEmojiProgressBar(BaseDownloadProgressBar, # type: ignore
  177. BlueEmojiBar):
  178. pass
  179. class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin,
  180. DownloadProgressMixin, Spinner):
  181. file = sys.stdout
  182. suffix = "%(downloaded)s %(download_speed)s"
  183. def next_phase(self): # type: ignore
  184. if not hasattr(self, "_phaser"):
  185. self._phaser = itertools.cycle(self.phases)
  186. return next(self._phaser)
  187. def update(self):
  188. # type: () -> None
  189. message = self.message % self
  190. phase = self.next_phase()
  191. suffix = self.suffix % self
  192. line = ''.join([
  193. message,
  194. " " if message else "",
  195. phase,
  196. " " if suffix else "",
  197. suffix,
  198. ])
  199. self.writeln(line)
  200. BAR_TYPES = {
  201. "off": (DownloadSilentBar, DownloadSilentBar),
  202. "on": (DefaultDownloadProgressBar, DownloadProgressSpinner),
  203. "ascii": (DownloadBar, DownloadProgressSpinner),
  204. "pretty": (DownloadFillingCirclesBar, DownloadProgressSpinner),
  205. "emoji": (DownloadBlueEmojiProgressBar, DownloadProgressSpinner)
  206. }
  207. def DownloadProgressProvider(progress_bar, max=None): # type: ignore
  208. if max is None or max == 0:
  209. return BAR_TYPES[progress_bar][1]().iter
  210. else:
  211. return BAR_TYPES[progress_bar][0](max=max).iter