Skip to content

Commit

Permalink
Add SpinnerMessage helper class
Browse files Browse the repository at this point in the history
This class provides a single interface for spinner strings where we
ideally want to report Unicode but want to fall back to ASCII when the
terminal doesn't support it.
  • Loading branch information
brettcs committed Aug 20, 2021
1 parent 8c8a29e commit db680f8
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions src/tox/util/spinner.py
Expand Up @@ -5,7 +5,7 @@
import os
import sys
import threading
from collections import OrderedDict
from collections import OrderedDict, namedtuple
from datetime import datetime

import py
Expand All @@ -19,34 +19,29 @@ class _CursorInfo(ctypes.Structure):
_fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]


def _file_support_encoding(chars, file):
encoding = getattr(file, "encoding", None)
if encoding is not None:
for char in chars:
try:
char.encode(encoding)
except UnicodeEncodeError:
break
_BaseMessage = namedtuple("_BaseMessage", ["unicode_msg", "ascii_msg"])


class SpinnerMessage(_BaseMessage):
def for_file(self, file):
try:
self.unicode_msg.encode(file.encoding)
except (AttributeError, TypeError, UnicodeEncodeError):
return self.ascii_msg
else:
return True
return False
return self.unicode_msg


class Spinner(object):
CLEAR_LINE = "\033[K"
max_width = 120
UNICODE_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
ASCII_FRAMES = ["|", "-", "+", "x", "*"]
FRAMES = SpinnerMessage("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", "|-+x*")

def __init__(self, enabled=True, refresh_rate=0.1):
self.refresh_rate = refresh_rate
self.enabled = enabled
self._file = sys.stdout
self.frames = (
self.UNICODE_FRAMES
if _file_support_encoding(self.UNICODE_FRAMES, sys.stdout)
else self.ASCII_FRAMES
)
self.frames = self.FRAMES.for_file(self._file)
self.stream = py.io.TerminalWriter(file=self._file)
self._envs = OrderedDict()
self._frame_index = 0
Expand Down

0 comments on commit db680f8

Please sign in to comment.