Skip to content

terminal

terminal #

Terminal — a log as lines on a stream; the file sink is the same class on a file.

A terminal keeps the open entries redrawn in place ten times a second beneath the lines already printed; anything else gets one line as an entry is made, one as a scope closes, and a revised line at most once a second, since a stream cannot take a line back.

Terminal #

Bases: Sink

Print the log to stream: sys.stderr by default, or an open file.

with cg.logging.to(cg.logging.Terminal()):
    ...

with open("build.log", "a") as file, cg.logging.to(cg.logging.Terminal(file)):
    ...
Source code in capturegraph-lib/capturegraph/logging/terminal.py
class Terminal(Sink):
    """Print the log to ``stream``: ``sys.stderr`` by default, or an open file.

    ```python
    with cg.logging.to(cg.logging.Terminal()):
        ...

    with open("build.log", "a") as file, cg.logging.to(cg.logging.Terminal(file)):
        ...
    ```
    """

    def __init__(self, stream: IO[str] | None = None) -> None:
        """A sink on ``stream``, redrawing in place when it is a terminal."""
        self._stream = stream if stream is not None else sys.stderr
        self._live = self._stream.isatty()
        self._lock = threading.Lock()
        self._depth: dict[str, int] = {}
        self._open: dict[str, Entry] = {}
        self._printed_at: dict[str, float] = {}
        self._drawn = 0
        self._drawn_at = 0.0
        self._pending: Entry | None = None
        self._stop = threading.Event()
        self._thread: threading.Thread | None = None

    def start(self, log: Log) -> None:
        """Start redrawing when the stream is a terminal."""
        if self._live and self._thread is None:
            self._thread = threading.Thread(
                target=self._redraw_loop, name="cg-logging-tty", daemon=True
            )
            self._thread.start()

    def emit(self, entry: Entry) -> None:
        """Print what a stream can show of this change."""
        with self._lock:
            depth = self._depth_of(entry)
            was_open = entry.id in self._open
            if entry.status == "open":
                self._open[entry.id] = entry
            else:
                self._open.pop(entry.id, None)
            now = time.monotonic()
            if self._pending is not None and self._pending is not entry:
                self._commit_pending()
            if entry.revision == 0:
                self._printed_at[entry.id] = now
                if self._live:
                    self._pending = entry
                else:
                    self._print(line(entry, depth))
            elif not was_open and entry.status == "open":
                self._pending = None
                self._redraw_if_due(now)
            elif was_open and entry.status != "open":
                self._printed_at[entry.id] = now
                self._print(line(entry, depth, closing=True))
            elif self._live and entry.status == "open":
                self._redraw_if_due(now)
            elif now - self._printed_at.get(entry.id, 0.0) >= REPRINT_SECONDS:
                self._printed_at[entry.id] = now
                self._print(line(entry, depth))

    def finish(self) -> None:
        """Stop redrawing, leaving the last frame on the terminal."""
        self._stop.set()
        if self._thread is not None:
            self._thread.join()
            self._thread = None
        with self._lock:
            self._commit_pending()
            if self._live:
                self._redraw()
        self._stream.flush()

    def _depth_of(self, entry: Entry) -> int:
        depth = self._depth.get(entry.id)
        if depth is None:
            above = self._depth.get(entry.parent, -1) if entry.parent is not None else -1
            depth = self._depth[entry.id] = above + 1
        return depth

    def _commit_pending(self) -> None:
        """A created entry nothing opened is a plain line; print it now."""
        pending, self._pending = self._pending, None
        if pending is not None and pending.id not in self._open:
            self._print(line(pending, self._depth_of(pending)))

    def _redraw_if_due(self, now: float) -> None:
        if self._live and now - self._drawn_at >= REDRAW_SECONDS:
            self._redraw()

    def _print(self, text: str) -> None:
        if self._live:
            self._erase()
        self._stream.write(f"{text}\n")
        if self._live:
            self._draw()
        self._stream.flush()

    def _redraw_loop(self) -> None:
        while not self._stop.wait(REDRAW_SECONDS):
            with self._lock:
                self._commit_pending()
                self._redraw()

    def _redraw(self) -> None:
        self._erase()
        self._draw()
        self._stream.flush()
        self._drawn_at = time.monotonic()

    def _erase(self) -> None:
        if self._drawn:
            self._stream.write(f"\x1b[{self._drawn}A")
        self._drawn = 0

    def _draw(self) -> None:
        for entry in self._open.values():
            self._stream.write(f"\x1b[2K{line(entry, self._depth.get(entry.id, 0))}\n")
        self._drawn = len(self._open)

__init__(stream=None) #

A sink on stream, redrawing in place when it is a terminal.

Source code in capturegraph-lib/capturegraph/logging/terminal.py
def __init__(self, stream: IO[str] | None = None) -> None:
    """A sink on ``stream``, redrawing in place when it is a terminal."""
    self._stream = stream if stream is not None else sys.stderr
    self._live = self._stream.isatty()
    self._lock = threading.Lock()
    self._depth: dict[str, int] = {}
    self._open: dict[str, Entry] = {}
    self._printed_at: dict[str, float] = {}
    self._drawn = 0
    self._drawn_at = 0.0
    self._pending: Entry | None = None
    self._stop = threading.Event()
    self._thread: threading.Thread | None = None

emit(entry) #

Print what a stream can show of this change.

Source code in capturegraph-lib/capturegraph/logging/terminal.py
def emit(self, entry: Entry) -> None:
    """Print what a stream can show of this change."""
    with self._lock:
        depth = self._depth_of(entry)
        was_open = entry.id in self._open
        if entry.status == "open":
            self._open[entry.id] = entry
        else:
            self._open.pop(entry.id, None)
        now = time.monotonic()
        if self._pending is not None and self._pending is not entry:
            self._commit_pending()
        if entry.revision == 0:
            self._printed_at[entry.id] = now
            if self._live:
                self._pending = entry
            else:
                self._print(line(entry, depth))
        elif not was_open and entry.status == "open":
            self._pending = None
            self._redraw_if_due(now)
        elif was_open and entry.status != "open":
            self._printed_at[entry.id] = now
            self._print(line(entry, depth, closing=True))
        elif self._live and entry.status == "open":
            self._redraw_if_due(now)
        elif now - self._printed_at.get(entry.id, 0.0) >= REPRINT_SECONDS:
            self._printed_at[entry.id] = now
            self._print(line(entry, depth))

finish() #

Stop redrawing, leaving the last frame on the terminal.

Source code in capturegraph-lib/capturegraph/logging/terminal.py
def finish(self) -> None:
    """Stop redrawing, leaving the last frame on the terminal."""
    self._stop.set()
    if self._thread is not None:
        self._thread.join()
        self._thread = None
    with self._lock:
        self._commit_pending()
        if self._live:
            self._redraw()
    self._stream.flush()

start(log) #

Start redrawing when the stream is a terminal.

Source code in capturegraph-lib/capturegraph/logging/terminal.py
def start(self, log: Log) -> None:
    """Start redrawing when the stream is a terminal."""
    if self._live and self._thread is None:
        self._thread = threading.Thread(
            target=self._redraw_loop, name="cg-logging-tty", daemon=True
        )
        self._thread.start()

bar(done, total) #

[####----] for done of total.

Source code in capturegraph-lib/capturegraph/logging/terminal.py
def bar(done: int, total: int) -> str:
    """``[####----]`` for ``done`` of ``total``."""
    filled = min(BAR_WIDTH, BAR_WIDTH * done // total) if total else BAR_WIDTH
    return f"[{'#' * filled}{'-' * (BAR_WIDTH - filled)}]"

line(entry, depth, *, closing=False) #

One line for entry at depth; a closing scope says done or failed.

Source code in capturegraph-lib/capturegraph/logging/terminal.py
def line(entry: Entry, depth: int, *, closing: bool = False) -> str:
    """One line for ``entry`` at ``depth``; a closing scope says ``done`` or ``failed``."""
    parts = [f"{'  ' * depth}{entry.message}"]
    parts.extend(f"{name}={value}" for name, value in entry.fields.items())
    if entry.total is not None:
        done = entry.done or 0
        parts.append(f"{bar(done, entry.total)} {done}/{entry.total}")
    elif entry.done:
        parts.append(str(entry.done))
    if closing:
        parts.append(f"{entry.status}  {entry.elapsed:.1f}s")
    elif entry.status == "open":
        parts.append(f"{entry.elapsed:.1f}s")
    if entry.iteration is not None:
        parts.append(f"(iteration {entry.iteration + 1})")
    text = "  ".join(parts)
    if entry.error is not None:
        indent = "  " * (depth + 1)
        text += "".join(f"\n{indent}{row}" for row in entry.error.splitlines())
    return text