kanbot-backend / cli /gumfx.py
LoveLogicAI's picture
Upload folder using huggingface_hub
587a933 verified
Raw History Blame Contribute Delete
3.91 kB
"""
gumfx — optional Charmbracelet `gum` polish for the human side of the CLI.
Charm's `gum` is a single Go binary that renders gorgeous shell UI (confirm,
choose, spinner, styled text). This module shells out to it WHEN PRESENT and
degrades gracefully when it isn't — so the CLI is prettier with gum installed
and fully functional without it. Zero Python deps.
HARD RULE: gum touches only the interactive HUMAN path. It is never invoked in
--json / agent mode (an agent must get clean machine output, never a TUI prompt).
Callers gate on `interactive` before using confirm/choose. Everything here also
respects NO_COLOR and a non-TTY stdout.
Install gum on the M4: brew install gum (or `go install github.com/charmbracelet/gum@latest`)
"""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
_GUM = shutil.which("gum")
# DevRev brand accent for gum styling.
VOLT = "#FFE600"
INK = "#161616"
def available() -> bool:
"""True if the gum binary is on PATH."""
return _GUM is not None
def interactive() -> bool:
"""True only when we should render human UI (TTY in+out, not agent/json mode)."""
return sys.stdin.isatty() and sys.stdout.isatty() and os.environ.get("NO_COLOR") is None
def style(text: str, *, accent: bool = False) -> str:
"""Return text styled by gum if available+interactive, else the plain text."""
if not (available() and interactive()):
return text
args = [_GUM, "style", "--padding", "0 1"]
if accent:
args += ["--foreground", INK, "--background", VOLT, "--bold"]
else:
args += ["--foreground", VOLT]
try:
out = subprocess.run(args + [text], capture_output=True, text=True, timeout=5)
return out.stdout.rstrip("\n") or text
except Exception:
return text
def confirm(prompt: str, *, default_yes: bool = False) -> bool:
"""A yes/no gate. gum confirm if available; plain input() fallback.
In non-interactive mode returns the default WITHOUT prompting (agents never
hit this path, but a piped human script gets deterministic behavior)."""
if not interactive():
return default_yes
if available():
try:
r = subprocess.run(
[_GUM, "confirm", prompt] + ([] if default_yes else ["--default=false"]),
timeout=120)
return r.returncode == 0 # gum exits 0 on yes
except Exception:
pass
ans = input(f"{prompt} [{'Y/n' if default_yes else 'y/N'}] ").strip().lower()
if not ans:
return default_yes
return ans in ("y", "yes")
def choose(prompt: str, options: list[str]) -> str | None:
"""Pick one of options. gum choose if available; numbered input() fallback."""
if not options:
return None
if not interactive():
return options[0]
if available():
try:
r = subprocess.run([_GUM, "choose", "--header", prompt, *options],
capture_output=True, text=True, timeout=120)
pick = r.stdout.strip()
return pick or None
except Exception:
pass
print(prompt)
for i, o in enumerate(options):
print(f" {i + 1}) {o}")
raw = input("pick #: ").strip()
if raw.isdigit() and 1 <= int(raw) <= len(options):
return options[int(raw) - 1]
return None
def spin(title: str, argv: list[str]) -> int:
"""Run a subprocess under a gum spinner if available; plain run otherwise.
Returns the child's exit code. Used to wrap slow ops like model pulls."""
if available() and interactive():
try:
r = subprocess.run([_GUM, "spin", "--spinner", "dot",
"--title", title, "--", *argv])
return r.returncode
except Exception:
pass
print(f"… {title}")
return subprocess.run(argv).returncode