Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions smpmgr/common.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
15 changes: 9 additions & 6 deletions smpmgr/file_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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__)
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions smpmgr/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
TransportDefinition,
connect_with_spinner,
get_smpclient,
replace_unencodable_output,
smp_request,
)
from smpmgr.image_management import (
Expand Down Expand Up @@ -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) "
Expand Down
8 changes: 8 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
33 changes: 33 additions & 0 deletions tests/test_spinner_progress.py
Original file line number Diff line number Diff line change
@@ -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"))
Loading