"""Terminal control, interactive paging, and ANSI color management."""
from __future__ import annotations
import io
import os
import shutil
import sys
from typing import TYPE_CHECKING, TextIO
if sys.version_info >= (3, 12):
from typing import override
else:
from typing_extensions import override
from rich.console import Console
from findfmt.utils.strings import _ANSI_ESCAPE_RE
if TYPE_CHECKING:
from collections.abc import Mapping
from rich.pager import Pager
__all__ = [
"PagerController",
"get_console",
"get_terminal_height",
"is_color_enabled",
"should_use_pager",
"strip_ansi",
]
_ANSI_REGEX = _ANSI_ESCAPE_RE
[docs]
def strip_ansi(text: str) -> str:
"""Remove ANSI escape sequences from text string.
Args:
text: Input string potentially containing ANSI escapes.
Returns:
Clean string free of ANSI escape sequences.
"""
return _ANSI_REGEX.sub("", text)
[docs]
def is_color_enabled(
stream: TextIO | None = None,
*,
env: Mapping[str, str] | None = None,
force_color: bool | None = None,
) -> bool:
"""Evaluate whether ANSI color sequences should be emitted.
Precedence order:
1. If force_color is explicitly set, its boolean value is honored.
2. If NO_COLOR is present and non-empty, color is disabled.
3. If CLICOLOR_FORCE is set and non-zero, color is forced.
4. If CLICOLOR is set to "0", color is disabled.
5. Otherwise, color is enabled only if stream is an interactive TTY.
Args:
stream: Target output text stream (defaults to sys.stdout).
env: Environment variable mapping override.
force_color: Explicit color enable override flag.
Returns:
True if colors should be emitted, False otherwise.
"""
if force_color is not None:
return force_color
active_env = os.environ if env is None else env
no_color_val = active_env.get("NO_COLOR")
if no_color_val is not None and no_color_val != "":
return False
force_val = active_env.get("CLICOLOR_FORCE")
if force_val is not None and force_val not in ("", "0"):
return True
clicolor_val = active_env.get("CLICOLOR")
if clicolor_val == "0":
return False
target = stream if stream is not None else sys.stdout
return bool(getattr(target, "isatty", lambda: False)())
class _PipeSafeConsole(Console):
"""Rich Console subclass that propagates BrokenPipeError to CLI signal handlers."""
@override
def on_broken_pipe(self) -> None:
"""Suppress further Console buffer writes and re-raise BrokenPipeError."""
self.quiet = True
raise BrokenPipeError
def _reconfigure_cp437(stream: TextIO) -> None:
"""Reconfigure text stream to CP437 encoding with replacement error handling."""
reconfigure = getattr(stream, "reconfigure", None)
if callable(reconfigure):
reconfigure(encoding="cp437", errors="replace")
[docs]
def get_console(
stream: TextIO | None = None,
*,
env: Mapping[str, str] | None = None,
width: int | None = None,
force_color: bool | None = None,
) -> Console:
"""Construct a Rich Console honoring environment variables and TTY settings.
Args:
stream: Target output text stream (defaults to sys.stdout).
env: Environment variable mapping override.
width: Optional terminal output column width override.
force_color: Explicit color enable override flag.
Returns:
Configured Rich Console instance.
"""
target = stream if stream is not None else sys.stdout
reconfigure = getattr(target, "reconfigure", None)
if callable(reconfigure) and getattr(target, "encoding", None) != "cp437":
reconfigure(errors="surrogateescape")
color_on = force_color if force_color is not None else is_color_enabled(target, env=env)
is_tty = getattr(target, "isatty", lambda: False)()
if not color_on:
return _PipeSafeConsole(
file=target,
no_color=True,
force_terminal=False,
width=width,
highlight=False,
)
if is_tty:
return _PipeSafeConsole(
file=target,
no_color=False,
width=width,
highlight=False,
)
return _PipeSafeConsole(
file=target,
no_color=False,
force_terminal=True,
color_system="standard",
width=width,
highlight=False,
)
[docs]
def get_terminal_height(fallback: int = 24) -> int:
"""Return current terminal height in lines with fallback.
Args:
fallback: Fallback row count when terminal size query fails.
Returns:
Detected terminal height row count.
"""
try:
height = shutil.get_terminal_size(fallback=(80, fallback)).lines
except (OSError, ValueError):
return fallback
else:
return height if height > 0 else fallback
class _StreamingPagerStream(io.StringIO):
"""Text stream that streams directly to TTY until exceeding one screenful."""
def __init__(self, pager_ctrl: PagerController) -> None:
"""Initialize streaming pager buffer for the given controller."""
super().__init__()
self._pager_ctrl = pager_ctrl
self._target = pager_ctrl.stream
self._color_active = is_color_enabled(
self._target,
env=pager_ctrl.env,
force_color=pager_ctrl.force_color,
)
self._pager_engaged = pager_ctrl.should_page(0)
@override
def write(self, s: str) -> int:
"""Write chunk to buffer and stream directly while below pager threshold."""
out = s if self._color_active else strip_ansi(s)
written = super().write(out)
if not self._pager_engaged:
if self._pager_ctrl.should_page(len(self.getvalue().splitlines())):
self._pager_engaged = True
else:
self._target.write(out)
self._target.flush()
return written
def finish(self) -> None:
"""Dispatch accumulated buffer to pager if screenful threshold was exceeded."""
if self._pager_engaged:
self._pager_ctrl.display(self.getvalue())