diff --git a/CHANGELOG.md b/CHANGELOG.md index ed7c762..5c17531 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,14 @@ one caveat SemVer makes for a leading zero: while the major version is still `0` somewhere, so a table added later starts being reported the day it lands — and the interesting count is always the table nobody expected to be full. + - **It saves to a file, for attaching rather than pasting.** `s` on the page writes + `meshterm-diagnostics.txt` into the config directory beside the log, and says so on the + page's own last line rather than in a dialog over the block you were about to read. + `meshterm diagnostics --out PATH` does the same from a shell, spelled the way + `config export-key --out` already spells it. The file is always the plain block, even + under `--json` — it exists to be read by a person — and it is laid out at full width, so + nothing is folded to whatever the terminal happened to be. + ### Changed - `--json` and the plain face grew a shared projection for a set of facts diff --git a/docs/cli.md b/docs/cli.md index f0c4272..cd47361 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1560,9 +1560,26 @@ a key of their own: {"meshterm":"0.3.7","install":"frozen","os":"Windows 11","…":"…","tables":[{"table":"observations","rows":418203}],"preferences":[{"preference":"log_level","value":"DEBUG"}]} ``` +**`--out PATH` writes it to a file instead of printing it**, and the answer becomes the +path — the same trade `config export-key --out` makes, since a caller who asked for a file +wants to be told where it is rather than handed the contents they just redirected into it. +The file is always the plain block, even under `--json`: it exists to be attached to an +issue and read by a person. Redirection still works and is not replaced; what `--out` adds +is a file laid out at full width rather than folded to whatever the terminal happened to be. + +```console +$ meshterm diagnostics --out meshterm-diagnostics.txt +✓ diagnostics written — attach it to the report. +/home/jp/meshterm-diagnostics.txt +``` + In the menu this is the **Diagnostics** page under *This app*, drawn on a bare frame — no border, no header, no footer, no key hints — because a terminal is selected by dragging and -every one of those is a character the clipboard would carry into the issue. +every one of those is a character the clipboard would carry into the issue. Its one line of +its own is `s save this to a file`, which writes `meshterm-diagnostics.txt` into the config +directory beside the log and then says so on that same line. A bare frame has nowhere else +to advertise a key, and one trailing line after a blank row costs a paste far less than a +border costs it on every line. #### `meshterm platform` diff --git a/meshterm/tools/diagnostics.py b/meshterm/tools/diagnostics.py index da7ed98..7c62be5 100644 --- a/meshterm/tools/diagnostics.py +++ b/meshterm/tools/diagnostics.py @@ -29,6 +29,7 @@ the block (``connected``/``error``) rather than an error that replaces it. from __future__ import annotations +from pathlib import Path from typing import TYPE_CHECKING, Any from ..context import AppContext @@ -42,6 +43,15 @@ if TYPE_CHECKING: # pragma: no cover - typing only #: cross-import between two tools to save five entries buys a dependency and no clarity. _ROLES = {1: "client", 2: "repeater", 3: "room server", 4: "sensor"} +#: What the saved file is called, in the config directory beside the log it sits next to +#: in a bug report. Named for the app rather than just ``diagnostics.txt`` because the one +#: thing that happens to this file is being moved somewhere else and attached, and by then +#: the directory it came from is no longer saying what it is. +#: +#: ``.txt`` and not ``.md``: the content is aligned columns, which markdown would reflow +#: into a paragraph, and a plain-text extension is the one every issue tracker accepts. +DIAGNOSTICS_FILENAME = "meshterm-diagnostics.txt" + @register class DiagnosticsTool(Tool): @@ -54,12 +64,36 @@ class DiagnosticsTool(Tool): category = "This app" order = 7 # after Preferences (the row that changes MeshTerm), before the pages + def register_cli(self, app: Any) -> None: + """Register the command, with the one option that turns the answer into a file. + + ``--out`` is spelled the way ``config export-key --out`` already spells it, rather + than inventing a second word for writing an answer to a path. Plain redirection + still works and is not replaced by it — what the option adds is a file whose + columns are laid out at full width instead of at whatever the terminal happened to + be, which is the difference between a readable attachment and a folded one. + """ + import typer + + from ..cli import run_tool_command + + @app.command(name=self.name, help=self.help) + def _command( + out: Path | None = typer.Option( + None, "--out", help="Write the block to this file instead of printing it" + ), + ) -> None: + run_tool_command(self, {"out": out}) + async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None: """Open the page in the menu; returning ``None`` completes with no run row. The same shape the About pages use: the menu's whole interaction *is* the screen, and a run row recording that somebody looked at their own version number would be - a line in the log for every glance. + a line in the log for every glance. Saving from the page is likewise not a run: + the page writes the file itself and says so on its own last line, because a + confirmation dialog over a page whose entire point is being unobstructed would + cover the thing it was confirming. Args: ctx: Shared application context. @@ -69,20 +103,35 @@ class DiagnosticsTool(Tool): """ from ..ui.diagnostics import open_diagnostics_page - await open_diagnostics_page(ctx, await build_report(ctx)) + await open_diagnostics_page(ctx, await build_report(ctx), save_path=default_path(ctx)) return None async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: - """State the diagnostics — only reachable from the CLI (the menu opens the screen). + """State the diagnostics, or write them to a file — only reachable from the CLI. + + With ``--out`` the answer *becomes the path*, the same trade ``config export-key`` + makes: a caller who asked for a file wants to be told where it is, not handed the + contents they just redirected into it. Args: ctx: Shared application context. - params: Unused beyond the injected ``_run_id``. + params: ``out`` — a destination path, or ``None`` to print the block. Returns: - A :class:`ToolResult` carrying the whole block as its report. + A :class:`ToolResult` carrying the block, or the path it was written to. """ - return ToolResult(summary={"tool": self.name}, report=await build_report(ctx)) + report = await build_report(ctx) + out = params.get("out") + if out is None: + return ToolResult(summary={"tool": self.name}, report=report) + + written = write_report(report, out) + ctx.ui.ack("[ok]✓[/ok] diagnostics written — attach it to the report.") + return ToolResult( + summary={"tool": self.name, "path": str(written)}, + artifacts=[str(written)], + report=(_written_to(written),), + ) async def build_report(ctx: AppContext) -> Report: @@ -111,6 +160,56 @@ async def build_report(ctx: AppContext) -> Report: ) +def default_path(ctx: AppContext) -> Path: + """Where the page saves when nobody named a place: beside the log, in the config dir. + + The config directory rather than the working directory, which in the menu is wherever + the reader happened to launch from and is not somewhere they can be told to look. It + is also where the log already lives, so "send me both" names one folder. + """ + return ctx.settings.config_dir / DIAGNOSTICS_FILENAME + + +def write_report(report: Report, path: Path | str) -> Path: + """Write a report's plain rendering to ``path``, creating its directory. + + **Always the plain face**, whatever the run was printing. A file exists here to be + attached to an issue and read by a person, and a document of the same facts helps that + person less than the block does; anyone who wants the machine face can redirect + ``--json`` and already has a better filename for it than this one. + + Args: + report: The block to write. + path: The destination. + + Returns: + The path written, resolved. + + Raises: + OSError: If the directory cannot be made or the file cannot be written. + """ + from ..ui.renderers import render_to_text + + written = Path(path) + written.parent.mkdir(parents=True, exist_ok=True) + written.write_text(render_to_text(report), encoding="utf-8") + return written + + +def _written_to(written: Path) -> Any: + """The answer a ``--out`` run gives: the path, alone on the plain face.""" + from ..ui import fields + from ..ui.report import BARE, Facts + + return Facts( + key="saved", + fields=(fields.path("path", "path"),), + values={"path": written}, + shape=BARE, + bare="path", + ) + + def _app_facts() -> Any: """What this program is: version, how it was installed, and where it keeps things.""" from .. import __version__ diff --git a/meshterm/ui/diagnostics.py b/meshterm/ui/diagnostics.py index f8c520b..c618b42 100644 --- a/meshterm/ui/diagnostics.py +++ b/meshterm/ui/diagnostics.py @@ -6,11 +6,16 @@ page is for is getting its text out of the terminal and into an issue, and a ter selected by dragging: a panel border is characters sitting on the *same lines* as the content, so every line of a line-wise selection arrives with a box-drawing glyph welded to each end. Same for a header, a footer hint and an F-key lane, which arrive as text that -looks like part of the report to whoever reads the paste. So this page draws its rows and -nothing at all besides (:attr:`~meshterm.ui.tui.screen.Screen.bare`), the same frame the -share screen uses for the same kind of reason — there, a camera wants no contrast arguing -with the code; here, a clipboard wants no furniture pretending to be data. Esc leaves, as -everywhere. +looks like part of the report to whoever reads the paste. So this page draws its rows on a +:attr:`~meshterm.ui.tui.screen.Screen.bare` frame, the one the share screen uses for the +same kind of reason — there, a camera wants no contrast arguing with the code; here, a +clipboard wants no furniture pretending to be data. Esc leaves, as everywhere. + +The page's **one** line of its own is the save hint, and that is a trade rather than an +exception: a bare frame has nowhere to advertise a key, so the alternative was a page that +could write the file and never said so. One trailing line after a blank row costs a paste +far less than a border costs it on every line, and a drag that follows the block stops +above it anyway (see :class:`DiagnosticsPage`). The rows come from the tool's :mod:`~meshterm.ui.report`, projected through the very lanes the command line prints (:func:`~meshterm.ui.renderers.facts_pairs`), so what is copied off @@ -23,6 +28,7 @@ own block instead (the app-wide rule for a wrapped labelled row). from __future__ import annotations +from pathlib import Path from typing import TYPE_CHECKING from rich.console import Group, RenderableType @@ -36,32 +42,90 @@ if TYPE_CHECKING: # pragma: no cover - typing only from .report import Facts, Listing, Report +#: The key that writes the block to a file, and the only affordance this page advertises. +SAVE_KEY = "s" + + class DiagnosticsPage(ScrollScreen): - """The bug-report block, full-screen and unadorned. + """The bug-report block, full-screen and unadorned, with one thing it can do. Bare, so a mouse drag takes the facts and only the facts; scrollable, because the block outgrows a 26-row console and a truncated bug report is worse than a scrolled - one. Read-only: there is nothing here to change, and the page is deliberately not a - place to change it from. + one. + + **The save line is the one concession, and it is a deliberate one.** A bare frame has + no footer and no F-key lane, so a page that could save and never said so would be a + key nobody could find — on the PicoCalc especially, where the lane is normally the only + place an affordance is advertised at all. So the page carries its own last line. It + costs a paste one trailing line where a border would have cost it a character on + *every* line, and a blank row above it means a drag that follows the block stops + before it of its own accord. + + Saving answers **on that same line** rather than in a dialog: the reader pressed a key + to be told where a file went, and a box over the page would cover the thing they were + about to copy. It is also what lets a failure — a read-only home, a full disk — be said + without inventing an error screen for it. """ bare = True - def __init__(self, report: Report) -> None: + def __init__(self, report: Report, *, save_path: Path) -> None: """Lay the report out as the page's body. Args: report: The tool's report — the same blocks the CLI renders. + save_path: Where :data:`SAVE_KEY` writes the block. """ - super().__init__(render_report(report), title="Diagnostics", floating=False) + super().__init__(Text(""), title="Diagnostics", floating=False) + self._report = report + self._save_path = save_path + self._saved: Path | None = None + self._error: str | None = None + self._refresh() + + def handle(self, action: str, data: str = "") -> None: + """Save on :data:`SAVE_KEY`; scroll or leave on everything else. + + The key arrives as bare text, which a read-only page can afford precisely because + it has no filter and no field for a letter to mean anything else in. + """ + if action == "text" and data.lower() == SAVE_KEY: + self._save() + return + super().handle(action, data) + + def _save(self) -> None: + """Write the block, and say on the page's own last line what happened.""" + from ..tools.diagnostics import write_report + + try: + self._saved, self._error = write_report(self._report, self._save_path), None + except OSError as exc: + # A home that is read-only, full, or not there. The reader can still copy the + # block off the screen, which is the whole reason that path exists as well. + self._saved, self._error = None, exc.strerror or str(exc) + self._refresh() + + def _refresh(self) -> None: + """Rebuild the body: the block, a blank row, then the page's one line of its own.""" + self.replace_content(Group(render_report(self._report), Text(""), self._status())) + + def _status(self) -> Text: + """The last line: what the key does, or what it did.""" + if self._error is not None: + return Text(f"could not save to {self._save_path}: {self._error}", style="err") + if self._saved is not None: + return Text(f"saved to {self._saved}", style="ok") + return Text(f"{SAVE_KEY} save this to a file", style="muted") -async def open_diagnostics_page(ctx: AppContext, report: Report) -> None: +async def open_diagnostics_page(ctx: AppContext, report: Report, *, save_path: Path) -> None: """Open the Diagnostics page full-screen and hold it until the reader backs out. Args: ctx: The shared application context (must be running the interactive TUI). report: The block to show. + save_path: Where the page's save key writes. Raises: RuntimeError: If called outside the interactive menu (no full-screen session). @@ -70,7 +134,7 @@ async def open_diagnostics_page(ctx: AppContext, report: Report) -> None: if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller raise RuntimeError("the Diagnostics page is only available in the menu") - await ctx.ui.session.run_screen(DiagnosticsPage(report)) + await ctx.ui.session.run_screen(DiagnosticsPage(report, save_path=save_path)) def render_report(report: Report) -> RenderableType: diff --git a/meshterm/ui/renderers.py b/meshterm/ui/renderers.py index 9f0b35b..8dc73b0 100644 --- a/meshterm/ui/renderers.py +++ b/meshterm/ui/renderers.py @@ -61,6 +61,46 @@ class OutputFormat(str, Enum): JSON = "json" +#: How wide a report is drawn when it is going into a *file* rather than onto a terminal. +#: Wide enough that no lane ever crops — a saved report exists to be complete, and the +#: table sizes each column to its content, so nothing is padded out to this either. +FILE_WIDTH = 200 + + +def render_to_text(report: Report | None, fmt: OutputFormat = OutputFormat.PLAIN) -> str: + """Render a report to a string, for writing somewhere that is not a terminal. + + The same renderers, on a capture console: a file gets exactly what the corresponding + face would have printed, so there is no third rendering to keep in step with the other + two. No colour, no highlighting and no markup interpretation — a node's name can + contain a bracket, and a file is read by things that do not speak SGR. + + Args: + report: The report to render, or ``None`` for nothing at all. + fmt: Which face to write. + + Returns: + The rendered text, newline-terminated where it has any content. + """ + console = Console( + width=FILE_WIDTH, + color_system=None, + highlight=False, + markup=False, + emoji=False, + # A capture must not consult the real terminal for its width or its legs. + force_terminal=False, + ) + with console.capture() as captured: + for_format(fmt, console).render(report) + # Rich pads every cell out to its column's width, which is invisible on a terminal and + # is trailing whitespace on disk — noise in a diff, and something a reader pasting the + # file onward has to strip. The written pages already do the same (see + # ``tools.about._rendered_page``). + text = "\n".join(line.rstrip() for line in captured.get().splitlines()) + return f"{text}\n" if text.strip() else "" + + def facts_pairs(block: Facts) -> list[tuple[str, str]]: """Project a :class:`Facts` block into its ``(key, value)`` text rows. diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index 42e02d4..fb5e2cd 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -204,9 +204,7 @@ def test_the_page_draws_no_chrome(ctx: AppContext) -> None: border, a header or a leading indent is a character the clipboard carries into the issue. """ - from meshterm.ui.diagnostics import DiagnosticsPage - - page = DiagnosticsPage(_report(ctx)) + page = _page(ctx) assert page.bare is True lines = [_strip(line) for line in page.render_body(72)] content = [line for line in lines if line.strip()] @@ -214,6 +212,89 @@ def test_the_page_draws_no_chrome(ctx: AppContext) -> None: assert not content[0].startswith(" ") +# --- saving it ------------------------------------------------------------------------ + + +def test_the_saved_file_is_what_the_command_line_prints(ctx: AppContext, tmp_path: Path) -> None: + """The file holds the plain block, drawn wide enough that no lane is cropped. + + Always the plain face, whatever the run was printing: this file exists to be attached + to an issue and read by a person. + """ + from meshterm.tools.diagnostics import write_report + + report = _report(ctx) + written = write_report(report, tmp_path / "out.txt") + saved = written.read_text(encoding="utf-8") + assert saved.strip() + for block in report: + if isinstance(block, Facts): + for key, value in facts_pairs(block): + assert key in saved + assert value in saved + + +def test_saving_creates_the_directory_it_needs(ctx: AppContext, tmp_path: Path) -> None: + """A destination whose parent does not exist yet is made rather than refused.""" + from meshterm.tools.diagnostics import write_report + + written = write_report(_report(ctx), tmp_path / "nested" / "deeper" / "out.txt") + assert written.is_file() + + +def test_the_page_advertises_the_save_key_then_reports_where_it_went( + ctx: AppContext, tmp_path: Path +) -> None: + """The page names its one key, and answers on the same line once it is pressed. + + A bare frame has no footer to advertise a key from, so the page carries the hint + itself — and the confirmation replaces it rather than opening a dialog over the block + the reader is about to copy. + """ + from meshterm.ui.diagnostics import SAVE_KEY + + target = tmp_path / "saved" / "meshterm-diagnostics.txt" + page = _page(ctx, save_path=target) + assert "save this to a file" in _body(page) + + page.handle("text", SAVE_KEY) + assert target.is_file() + # Matched in two parts because a tmp_path is long enough to wrap the status line, + # which is the line behaving correctly rather than a failure. + body = _body(page) + assert "saved to" in body + assert target.name in body + assert "save this to a file" not in body + + +def test_a_save_that_fails_is_said_on_the_page_not_raised(ctx: AppContext, tmp_path: Path) -> None: + """An unwritable destination leaves the block readable and explains itself. + + The block on screen is still copyable, which is the whole reason that path exists + alongside the file — so a failed write must never take the page down with it. + """ + from meshterm.ui.diagnostics import SAVE_KEY + + # A path whose "directory" is an existing file: mkdir and write both refuse, on + # every OS, without needing permissions the suite cannot count on. + blocker = tmp_path / "blocker" + blocker.write_text("not a directory", encoding="utf-8") + page = _page(ctx, save_path=blocker / "inside" / "out.txt") + + page.handle("text", SAVE_KEY) + body = _body(page) + assert "could not save" in body + assert "meshterm" in body # the block itself is untouched + + +def test_the_save_key_is_the_only_letter_the_page_claims(ctx: AppContext, tmp_path: Path) -> None: + """Any other letter falls through to the scroll handler rather than doing something.""" + page = _page(ctx, save_path=tmp_path / "out.txt") + page.handle("text", "q") + assert not (tmp_path / "out.txt").exists() + assert "save this to a file" in _body(page) + + def test_an_empty_listing_is_drawn_by_neither_face() -> None: """A listing with no rows is absent from the page exactly as it is from the output. @@ -360,3 +441,16 @@ def _console(width: int) -> Console: def _strip(line: str) -> str: """One rendered line with its SGR runs removed.""" return re.sub(r"\x1b\[[0-9;]*m", "", line) + + +def _page(ctx: AppContext, *, save_path: Path | None = None): + """The page over this context's report, saving wherever the caller wants.""" + from meshterm.ui.diagnostics import DiagnosticsPage + + target = save_path or (ctx.settings.config_dir / "meshterm-diagnostics.txt") + return DiagnosticsPage(_report(ctx), save_path=target) + + +def _body(page) -> str: + """The page's drawn rows as plain text.""" + return "\n".join(_strip(line) for line in page.render_body(100)) diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 077e225..6e9fdd2 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -993,7 +993,10 @@ def _diagnostics(cols: int, rows: int) -> Screen: """ from meshterm.ui.diagnostics import DiagnosticsPage - return DiagnosticsPage(_diagnostics_report()) + return DiagnosticsPage( + _diagnostics_report(), + save_path=Path("C:/Users/somebody/.meshterm/meshterm-diagnostics.txt"), + ) def _diagnostics_report():