diff --git a/smpmgr/common.py b/smpmgr/common.py index 67541c3..fb7ce25 100644 --- a/smpmgr/common.py +++ b/smpmgr/common.py @@ -1,11 +1,15 @@ """Common CLI helpers from rich, typer, click, etc.""" import asyncio +import io import logging +import sys from dataclasses import dataclass, fields from typing import Final, Type, TypedDict, TypeVar, assert_never import typer +from rich import get_console +from rich.console import Console from rich.progress import Progress, SpinnerColumn, TextColumn from serial import SerialException from smp.exceptions import SMPBadStartDelimiter @@ -125,11 +129,25 @@ def get_smpclient(options: Options) -> SMPClient: return get_custom_smpclient(options, SMPClient) +def replace_unencodable_output() -> None: + """Write `?` for what stdout and stderr cannot encode, rather than raising.""" + for stream in (sys.stdout, sys.stderr): + if isinstance(stream, io.TextIOWrapper): + stream.reconfigure(errors="replace") + + +def spinner_progress(console: Console) -> Progress: + """A spinner and description that the console can draw.""" + return Progress( + SpinnerColumn("line" if console.legacy_windows or console.options.ascii_only else "dots"), + TextColumn("[progress.description]{task.description}"), + console=console, + ) + + async def connect_with_spinner(smpclient: SMPClient) -> None: """Spin while connecting to the SMP Server; raises `typer.Exit` if connection fails.""" - with Progress( - SpinnerColumn(), TextColumn("[progress.description]{task.description}") - ) as progress: + with spinner_progress(get_console()) as progress: connect_task_description = f"Connecting to {smpclient._address}..." connect_task = progress.add_task(description=connect_task_description, total=None) try: @@ -155,9 +173,7 @@ async def smp_request( description: str | None = None, timeout_s: float | None = None, ) -> TRep | TEr1 | TEr2: - with Progress( - SpinnerColumn(), TextColumn("[progress.description]{task.description}") - ) as progress: + with spinner_progress(get_console()) as progress: description = description or f"Waiting for response to {request.__class__.__name__}..." task = progress.add_task(description=description, total=None) try: diff --git a/smpmgr/file_management.py b/smpmgr/file_management.py index 3f09193..03aacae 100644 --- a/smpmgr/file_management.py +++ b/smpmgr/file_management.py @@ -7,12 +7,11 @@ from typing import cast import typer -from rich import print +from rich import get_console, print from rich.progress import ( BarColumn, DownloadColumn, Progress, - SpinnerColumn, TextColumn, TimeRemainingColumn, TransferSpeedColumn, @@ -27,7 +26,13 @@ ) from typing_extensions import Annotated -from smpmgr.common import Options, connect_with_spinner, get_smpclient, smp_request +from smpmgr.common import ( + Options, + connect_with_spinner, + get_smpclient, + smp_request, + spinner_progress, +) app = typer.Typer(name="file", help="The SMP File Management Group.") logger = logging.getLogger(__name__) @@ -175,9 +180,7 @@ def download( async def f() -> None: await connect_with_spinner(smpclient) - with Progress( - SpinnerColumn(), TextColumn("[progress.description]{task.description}") - ) as progress: + with spinner_progress(get_console()) as progress: download_task = progress.add_task(description=f"Downloading {file}", total=None) file_data = await smpclient.download_file(file) progress.update(download_task, description=f"Downloaded {file}", completed=True) diff --git a/smpmgr/main.py b/smpmgr/main.py index f48f43d..c0969b6 100644 --- a/smpmgr/main.py +++ b/smpmgr/main.py @@ -34,6 +34,7 @@ TransportDefinition, connect_with_spinner, get_smpclient, + replace_unencodable_output, smp_request, ) from smpmgr.image_management import ( @@ -139,6 +140,8 @@ def options( None, help="Path to plugin directory. May be used more than once." ), ) -> None: + replace_unencodable_output() + if plugin_path: raise ValueError( "--plugin-path should have been removed from sys.argv by the get_plugins(sys.argv) " diff --git a/tests/test_cli.py b/tests/test_cli.py index 9632770..52914fa 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -50,3 +50,11 @@ def test_global_options_parse_without_running_command(transport: tuple[str, str] ) assert result.exit_code == 0, result.output + + +def test_cp1252_output_replaces_what_it_cannot_encode() -> None: + result = CliRunner(charset="cp1252").invoke(app, ["--port", "/dev/☃", "os", "echo", "hi"]) + + assert isinstance(result.exception, SystemExit), result.exception + assert result.exit_code == 1 + assert "Connecting to /dev/?..." in result.output diff --git a/tests/test_spinner_progress.py b/tests/test_spinner_progress.py new file mode 100644 index 0000000..b3dbe02 --- /dev/null +++ b/tests/test_spinner_progress.py @@ -0,0 +1,33 @@ +import io + +import pytest +from rich.console import Console + +from smpmgr.common import spinner_progress + + +def _render(encoding: str, *, legacy_windows: bool = False) -> str: + raw = io.BytesIO() + console = Console( + file=io.TextIOWrapper(raw, encoding=encoding), + force_terminal=True, + legacy_windows=legacy_windows, + ) + with spinner_progress(console) as progress: + progress.add_task(description="Connecting...", total=None) + progress.refresh() + console.file.flush() + return raw.getvalue().decode(encoding) + + +@pytest.mark.parametrize("encoding", ["cp1252", "ascii"]) +def test_spinner_progress_draws_ascii_on_a_non_utf_console(encoding: str) -> None: + assert _render(encoding).isascii() + + +def test_spinner_progress_draws_ascii_on_a_legacy_windows_console() -> None: + assert _render("utf-8", legacy_windows=True).isascii() + + +def test_spinner_progress_keeps_the_braille_spinner_on_a_utf8_console() -> None: + assert any("⠀" <= c <= "⣿" for c in _render("utf-8"))