Add arrow-key menus and report loading status

wizard: when stdin and stdout are both TTYs, menus render inline and
are driven by keys: up/down/j/k/Home/End move the bold '>' highlight,
Enter accepts, Esc/Ctrl-C/q back out of cancellable menus while Ctrl-C
on fixed menus still aborts. Rows redraw with erase+CR across the
option block only and clear before returning so prompts stay aligned.
Non-TTY stdio keeps the original numbered prompt verbatim.

report: each configured source shows a transient "# Generating
report: pulling <name> data..." line that is erased on completion,
only when stdout is a TTY; piped output remains exactly the report.

tests: cover the numbered fallback, row rendering, status suppression
and show+clear parity; reformat stray test files to satisfy ruff.
This commit is contained in:
2026-08-27 07:46:48 +00:00
parent 5f4487f3ad
commit 85ddfb4a71
6 changed files with 340 additions and 28 deletions
+44 -2
View File
@@ -8,7 +8,13 @@ from collections.abc import Sequence
from datetime import UTC, datetime
from pathlib import Path
from weekly_activity.aggregate import build_specs, collect_specs, format_combined
from weekly_activity.aggregate import (
Collected,
SourceSpec,
build_specs,
collect_specs,
format_combined,
)
from weekly_activity.config import ConfigError, default_config_path, load_config
from weekly_activity.model import last_week_window
from weekly_activity.report import format_report
@@ -128,6 +134,42 @@ def resolve_period(args: argparse.Namespace) -> tuple[datetime, datetime]:
return last_week_window()
_STATUS_PREFIX = "# Generating report"
_STATUS_ERASE = "\x1b[2K\r"
def _report_status_active() -> bool:
"""Transient progress lines only make sense on an interactive terminal."""
return sys.stdout.isatty()
def _show_report_status(name: str) -> None:
"""Erase-then-overwrite in place; no newline keeps updates on one row."""
sys.stdout.write(f"{_STATUS_ERASE}{_STATUS_PREFIX}: pulling {name} data...")
sys.stdout.flush()
def _hide_report_status() -> None:
"""Erase the status row so nothing of it survives into the final output."""
sys.stdout.write(_STATUS_ERASE)
sys.stdout.flush()
def _collect_report_sources(
specs: list[SourceSpec], since: datetime, until: datetime
) -> list[Collected]:
"""Run collect_specs per source, showing a TTY-only progress line each."""
show = _report_status_active()
collected: list[Collected] = []
for spec in specs:
if show:
_show_report_status(spec.name)
collected.extend(collect_specs([spec], since, until))
if show:
_hide_report_status()
return collected
def main() -> None:
args = parse_args()
command = args.command or "report"
@@ -150,7 +192,7 @@ def main() -> None:
if not specs:
raise SystemExit(f"error: {path} enables no sources; run `weekly-activity config`.")
since, until = resolve_period(args)
collected = collect_specs(specs, since, until)
collected = _collect_report_sources(specs, since, until)
print(format_combined(collected, since, until))
return
+126 -1
View File
@@ -286,7 +286,17 @@ def _display_name(account: object) -> str:
def _menu(title: str, options: Sequence[str], *, cancellable: bool = False) -> int | None:
"""Numbered-choice menu: selected index, or None when backed out."""
"""Pick an option: interactive arrows on a TTY, numbered prompt otherwise.
Returns the selected index, or None when backed out of a cancellable menu.
"""
if sys.stdin.isatty() and sys.stdout.isatty():
return _arrow_menu(title, options, cancellable=cancellable)
return _numbered_menu(title, options, cancellable=cancellable)
def _numbered_menu(title: str, options: Sequence[str], *, cancellable: bool = False) -> int | None:
"""Numbered-choice fallback for non-TTY stdin (piped input, tests, CI)."""
print(title)
for number, option in enumerate(options, 1):
print(f" {number}) {option}")
@@ -307,6 +317,121 @@ def _menu(title: str, options: Sequence[str], *, cancellable: bool = False) -> i
print(f"Please enter a number between 1 and {valid}.")
# --- Arrow-key menu (interactive TTYs only) ---
_BOLD = "\x1b[1m"
_RESET = "\x1b[0m"
_ERASE_LINE = "\x1b[2K"
_CURSOR_DOWN = "\x1b[1B"
_CURSOR_UP_TEMPLATE = "\x1b[{}A"
# Key classifications shared by the reader and the menu loop.
_KEY_UP = "up"
_KEY_DOWN = "down"
_KEY_HOME = "home"
_KEY_END = "end"
_KEY_ENTER = "enter"
_KEY_ESCAPE = "escape"
_KEY_OTHER = "other"
_CSI_KEYS = {"[A": _KEY_UP, "[B": _KEY_DOWN, "[H": _KEY_HOME, "[F": _KEY_END}
def _read_keypress() -> str:
"""Read one keystroke from stdin (cbreak mode); classify it."""
import select
char = sys.stdin.read(1)
if char == "\x1b":
# A bare Esc is not followed by more bytes; CSI sequences are. Peek briefly.
readable, _, _ = select.select([sys.stdin], [], [], 0.05)
if not readable:
return _KEY_ESCAPE
tail = sys.stdin.read(2)
return _CSI_KEYS.get(tail, _KEY_OTHER)
if char in ("\r", "\n"):
return _KEY_ENTER
if char == "\x01": # Ctrl-A
return _KEY_HOME
if char == "\x05": # Ctrl-E
return _KEY_END
if char == "k":
return _KEY_UP
if char == "j":
return _KEY_DOWN
return _KEY_OTHER
def _option_line(option: str, selected: bool) -> str:
"""One rendered row: bold with a '>' marker on the selected line."""
prefix = "> " if selected else " "
if selected:
return f"{_BOLD}{prefix}{option}{_RESET}"
return f"{prefix}{option}"
def _draw_menu_rows(options: Sequence[str], selected: int | None) -> None:
"""Redraw or clear the option rows.
On entry the cursor sits at column 0 of the blank row just below the
block; writes move up and repaint each row so the title above stays
untouched. With ``selected=None`` every row is erased instead,
clearing the menu before trailing prompts run.
"""
out = sys.stdout
out.write(_CURSOR_UP_TEMPLATE.format(len(options)))
for index, option in enumerate(options):
out.write(_ERASE_LINE + "\r")
if selected is not None:
out.write(_option_line(option, index == selected))
out.write(_CURSOR_DOWN)
out.flush()
def _arrow_menu(title: str, options: Sequence[str], *, cancellable: bool = False) -> int | None:
"""Inline re-rendered menu driven by raw-mode keypresses."""
import termios
import tty
print(title)
selected = 0
for index, option in enumerate(options): # fresh draw lands one row per option
print(_option_line(option, index == selected))
fd = sys.stdin.fileno()
saved_state = termios.tcgetattr(fd)
choice: int | None = None
try:
tty.setcbreak(fd)
while True:
key = _read_keypress()
if key == _KEY_ENTER:
choice = selected
break
if key == _KEY_UP:
selected = (selected - 1) % len(options)
elif key == _KEY_DOWN:
selected = (selected + 1) % len(options)
elif key == _KEY_HOME:
selected = 0
elif key == _KEY_END:
selected = len(options) - 1
elif cancellable and key in (_KEY_ESCAPE, "q"):
break
else: # Esc/q on fixed menus, or any unrecognised key: no-op.
continue
_draw_menu_rows(options, selected)
except KeyboardInterrupt:
# ISIG stays enabled under cbreak, so Ctrl-C raises SIGINT here.
if not cancellable:
raise
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, saved_state)
_draw_menu_rows(options, None)
return choice
def _ask(prompt: str, default: str = "") -> str:
suffix = f" [{default}]" if default else ""
answer = input(f"{prompt}{suffix}: ").strip()