progress_bars.py 8.1 KB

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