From cbccdd3981dc057c945f6dd3e991c9d4c4c71c62 Mon Sep 17 00:00:00 2001 From: JP Hutchins Date: Tue, 10 Nov 2026 16:58:04 -0800 Subject: [PATCH] fix: never crash on output the console's encoding cannot represent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When stdout's encoding cannot represent a character smpmgr writes, Python raises and the command aborts. That happens on a Windows console with the cp1252 code page (#91), or on the pipe that a process wrapping the smpmgr executable reads (#104): UnicodeEncodeError: 'charmap' codec can't encode character '⠴' in position 0: character maps to The first character to fail is Rich's braille spinner, but it is not the only one. A transport address, BLE name or file path in a task description can fail too (`--port /dev/☃` on cp1252), as can the "•" separator of the upload progress bars on ascii/cp437, and Rich tracebacks. Two layers: - replace_unencodable_output(), called first in the CLI callback, reconfigures stdout and stderr with errors="replace". A character the stream cannot encode is written as "?" instead of raising, on every output path at once. - spinner_progress() builds every spinner Progress: connect_with_spinner, smp_request, and `file download`, which #104 missed. It keeps "dots", but draws Rich's ASCII "line" spinner where Rich's own ProgressBar falls back to ASCII (`legacy_windows or options.ascii_only`, rich progress_bar.py). The spinner then animates instead of degrading to "?". It takes Rich's global console, so RichHandler log records still render above the live spinner, and FORCE_COLOR / TTY_COMPATIBLE detection is unchanged. Compared with #104 as first proposed: that version forced the "line" spinner on everyone and gave each Progress a private `Console(force_terminal=sys.stdout.isatty())`. The private console separated the spinner from the console RichHandler logs through, so log lines collide with the spinner. force_terminal overrode Rich's environment detection, and `sys.stdout.isatty()` raises when sys.stdout is None. Its unrelated black reformat of main.py is dropped. PEP 686 makes UTF-8 mode the default in Python 3.15, but the executables are still built on 3.12 (build.yaml), so this still matters. Building them in UTF-8 mode would be the other route. Verified, with PYTHONIOENCODING=cp1252 and stdout piped: `smpmgr --port /dev/does-not-exist os echo hi` crashes on main with the error above, and `--port /dev/☃` crashes on '☃'. With this change they print "/ Connecting to /dev/does-not-exist... error" and "/ Connecting to /dev/?... error", and exit 1. In tests: - test_cp1252_output_replaces_what_it_cannot_encode drives the CLI with a cp1252 stdout. With replace_unencodable_output stubbed out, the same invocation raises UnicodeEncodeError. - tests/test_spinner_progress.py checks for ASCII-only output on cp1252, ascii and legacy Windows consoles, and braille kept on UTF-8. Co-authored-by: Filip Co-Authored-By: claude-opus-5-5 --- smpmgr/common.py | 28 ++++++++++++++++++++++------ smpmgr/file_management.py | 15 +++++++++------ smpmgr/main.py | 3 +++ tests/test_cli.py | 8 ++++++++ tests/test_spinner_progress.py | 33 +++++++++++++++++++++++++++++++++ 5 files changed, 75 insertions(+), 12 deletions(-) create mode 100644 tests/test_spinner_progress.py 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"))