feat: add color to spinner

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
This commit is contained in:
dw-0
2024-08-11 16:05:11 +02:00
parent 3e6d3d9015
commit f60d0b923c

View File

@@ -1,28 +1,55 @@
import sys import sys
import threading import threading
import time import time
from typing import List from typing import List, Literal
from core.constants import (
COLOR_GREEN,
COLOR_RED,
COLOR_WHITE,
COLOR_YELLOW,
RESET_FORMAT,
)
SpinnerColor = Literal["white", "red", "green", "yellow"]
class Spinner: class Spinner:
def __init__(self, message: str = "Loading", delay: float = 0.2) -> None: def __init__(
self,
message: str = "Loading",
color: SpinnerColor = "white",
interval: float = 0.2,
) -> None:
self.message = f"{message} ..." self.message = f"{message} ..."
self.delay = delay self.interval = interval
self._stop_event = threading.Event() self._stop_event = threading.Event()
self._thread = threading.Thread(target=self._animate) self._thread = threading.Thread(target=self._animate)
self._color = ""
self._set_color(color)
def _animate(self) -> None: def _animate(self) -> None:
animation: List[str] = ["", "", "", ""] animation: List[str] = ["", "", "", "", "", "", "", "", "", ""]
while not self._stop_event.is_set(): while not self._stop_event.is_set():
for char in animation: for char in animation:
sys.stdout.write(f"\r{char} {self.message}") sys.stdout.write(f"\r{self._color}{char}{RESET_FORMAT} {self.message}")
sys.stdout.flush() sys.stdout.flush()
time.sleep(self.delay) time.sleep(self.interval)
if self._stop_event.is_set(): if self._stop_event.is_set():
break break
sys.stdout.write("\r" + " " * (len(self.message) + 1) + "\r") sys.stdout.write("\r" + " " * (len(self.message) + 1) + "\r")
sys.stdout.flush() sys.stdout.flush()
def _set_color(self, color: SpinnerColor) -> None:
if color == "white":
self._color = COLOR_WHITE
elif color == "red":
self._color = COLOR_RED
elif color == "green":
self._color = COLOR_GREEN
elif color == "yellow":
self._color = COLOR_YELLOW
def start(self) -> None: def start(self) -> None:
self._stop_event.clear() self._stop_event.clear()
if not self._thread.is_alive(): if not self._thread.is_alive():