Rewrite the status line in Python, and test it
This commit is contained in:
Executable
+122
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
import datetime
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
CYAN = "\033[36m"
|
||||
DIM = "\033[2m"
|
||||
GREEN = "\033[32m"
|
||||
RED = "\033[31m"
|
||||
RESET = "\033[0m"
|
||||
YELLOW = "\033[33m"
|
||||
|
||||
|
||||
def field(status: object, *path: str) -> object:
|
||||
for key in path:
|
||||
if not isinstance(status, dict):
|
||||
return None
|
||||
status = status.get(key)
|
||||
return status
|
||||
|
||||
|
||||
def number(status: object, *path: str) -> float | None:
|
||||
found = field(status, *path)
|
||||
return found if isinstance(found, (int, float)) and not isinstance(found, bool) and math.isfinite(found) else None
|
||||
|
||||
|
||||
def text(status: object, *path: str) -> str:
|
||||
found = field(status, *path)
|
||||
return found if isinstance(found, str) else ""
|
||||
|
||||
|
||||
def directory(status: object) -> str:
|
||||
return text(status, "workspace", "current_dir") or text(status, "cwd")
|
||||
|
||||
|
||||
def usage_color(percent: int) -> str:
|
||||
return RED if percent >= 80 else YELLOW if percent >= 50 else GREEN
|
||||
|
||||
|
||||
def humanize_tokens(count: int) -> str:
|
||||
if count >= 1_000_000:
|
||||
return f"{count // 1_000_000}.{count % 1_000_000 // 100_000}M"
|
||||
if count >= 1000:
|
||||
return f"{count // 1000}k"
|
||||
return str(count)
|
||||
|
||||
|
||||
def reset_suffix(epoch: float, now: int, zone: datetime.tzinfo | None) -> str:
|
||||
at = datetime.datetime.fromtimestamp(round(epoch), zone)
|
||||
seconds = max(0, round(epoch) - now)
|
||||
if seconds >= 86400:
|
||||
left = f"{seconds // 86400}d{seconds % 86400 // 3600}h"
|
||||
elif seconds >= 3600:
|
||||
left = f"{seconds // 3600}h{seconds % 3600 // 60}m"
|
||||
else:
|
||||
left = f"{seconds // 60}m"
|
||||
clock = at.strftime("%H:%M" if at.date() == datetime.datetime.fromtimestamp(now, zone).date() else "%a %H:%M")
|
||||
return f" {DIM}{left} left ({clock}){RESET}"
|
||||
|
||||
|
||||
def usage(label: str, percent: float, suffix: str) -> str:
|
||||
rounded = round(percent)
|
||||
return f"{DIM}{label}{RESET} {usage_color(rounded)}{rounded}%{RESET}{suffix}"
|
||||
|
||||
|
||||
def limit(status: object, label: str, window: str, now: int, zone: datetime.tzinfo | None) -> list[str]:
|
||||
percent = number(status, "rate_limits", window, "used_percentage")
|
||||
if percent is None:
|
||||
return []
|
||||
resets = number(status, "rate_limits", window, "resets_at")
|
||||
return [usage(label, percent, "" if resets is None else reset_suffix(resets, now, zone))]
|
||||
|
||||
|
||||
def render(status: object, branch: str, home: str, now: int, zone: datetime.tzinfo | None) -> str:
|
||||
where = []
|
||||
shown = directory(status)
|
||||
if shown:
|
||||
if home and (shown == home or shown.startswith(home + "/")):
|
||||
shown = "~" + shown[len(home):]
|
||||
where.append(f"{CYAN}{shown}{RESET}")
|
||||
if branch:
|
||||
where.append(f"{DIM}{branch}{RESET}")
|
||||
model = text(status, "model", "display_name")
|
||||
if model:
|
||||
where.append(f"{DIM}{model}{RESET}")
|
||||
|
||||
load = []
|
||||
context = number(status, "context_window", "used_percentage")
|
||||
if context is not None:
|
||||
used, size = number(status, "context_window", "total_input_tokens"), number(status, "context_window", "context_window_size")
|
||||
tokens = "" if used is None or size is None else f" {DIM}{humanize_tokens(int(used))}/{humanize_tokens(int(size))}{RESET}"
|
||||
load.append(usage("ctx", context, tokens))
|
||||
load += limit(status, "5h", "five_hour", now, zone) + limit(status, "7d", "seven_day", now, zone)
|
||||
|
||||
return "\n".join(f"{DIM} | {RESET}".join(row) for row in (where, load) if row)
|
||||
|
||||
|
||||
def current_branch(where: str) -> str:
|
||||
if not where:
|
||||
return ""
|
||||
try:
|
||||
found = subprocess.run(["git", "-C", where, "branch", "--show-current"], capture_output=True, text=True)
|
||||
except OSError:
|
||||
return ""
|
||||
return found.stdout.strip() if found.returncode == 0 else ""
|
||||
|
||||
|
||||
def main(stdin: typing.TextIO, env: typing.Mapping[str, str]) -> str:
|
||||
try:
|
||||
status = json.load(stdin)
|
||||
except ValueError:
|
||||
status = None
|
||||
return render(status, current_branch(directory(status)), env.get("HOME", ""), int(time.time()), None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.write(main(sys.stdin, os.environ))
|
||||
@@ -0,0 +1,89 @@
|
||||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
import statusline
|
||||
from statusline import CYAN, DIM, GREEN, RED, RESET, YELLOW
|
||||
|
||||
NOW = int(datetime.datetime(2026, 10, 2, 12, 0, tzinfo=datetime.timezone.utc).timestamp())
|
||||
SEP = f"{DIM} | {RESET}"
|
||||
UTC = datetime.timezone.utc
|
||||
|
||||
|
||||
def render(status, branch="", home="/home/me"):
|
||||
return statusline.render(status, branch, home, NOW, UTC)
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_shows_every_field_on_two_rows(self):
|
||||
status = {
|
||||
"context_window": {"context_window_size": 1_000_000, "total_input_tokens": 85_000, "used_percentage": 42.5},
|
||||
"model": {"display_name": "Opus"},
|
||||
"rate_limits": {"five_hour": {"resets_at": NOW + 5000, "used_percentage": 63}, "seven_day": {"resets_at": NOW + 300_000, "used_percentage": 91.2}},
|
||||
"workspace": {"current_dir": "/home/me/code/a"},
|
||||
}
|
||||
self.assertEqual(render(status, "main"), "\n".join([
|
||||
SEP.join([f"{CYAN}~/code/a{RESET}", f"{DIM}main{RESET}", f"{DIM}Opus{RESET}"]),
|
||||
SEP.join([
|
||||
f"{DIM}ctx{RESET} {GREEN}42%{RESET} {DIM}85k/1.0M{RESET}",
|
||||
f"{DIM}5h{RESET} {YELLOW}63%{RESET} {DIM}1h23m left (13:23){RESET}",
|
||||
f"{DIM}7d{RESET} {RED}91%{RESET} {DIM}3d11h left (Mon 23:20){RESET}",
|
||||
]),
|
||||
]))
|
||||
|
||||
def test_shows_nothing_for_an_empty_or_unparsed_status(self):
|
||||
self.assertEqual(render({}), "")
|
||||
self.assertEqual(render(None), "")
|
||||
|
||||
def test_skips_a_field_of_the_wrong_type(self):
|
||||
status = {"context_window": {"used_percentage": "42"}, "cwd": 7, "model": {"display_name": None}, "rate_limits": {"five_hour": {"used_percentage": True}}}
|
||||
self.assertEqual(render(status), "")
|
||||
|
||||
def test_falls_back_to_cwd_and_shows_the_branch_only_beside_a_directory(self):
|
||||
self.assertEqual(render({"cwd": "/srv"}, "main"), SEP.join([f"{CYAN}/srv{RESET}", f"{DIM}main{RESET}"]))
|
||||
self.assertEqual(render({"model": {"display_name": "Opus"}}, "main"), f"{DIM}Opus{RESET}")
|
||||
|
||||
def test_abbreviates_home_only_at_a_path_boundary(self):
|
||||
self.assertEqual(render({"cwd": "/home/me"}), f"{CYAN}~{RESET}")
|
||||
self.assertEqual(render({"cwd": "/home/meg"}), f"{CYAN}/home/meg{RESET}")
|
||||
self.assertEqual(render({"cwd": "/home/me"}, home=""), f"{CYAN}/home/me{RESET}")
|
||||
|
||||
def test_omits_the_token_counts_unless_both_are_known(self):
|
||||
self.assertEqual(render({"context_window": {"total_input_tokens": 5, "used_percentage": 1}}), f"{DIM}ctx{RESET} {GREEN}1%{RESET}")
|
||||
|
||||
def test_omits_the_reset_unless_known(self):
|
||||
self.assertEqual(render({"rate_limits": {"five_hour": {"used_percentage": 50}}}), f"{DIM}5h{RESET} {YELLOW}50%{RESET}")
|
||||
|
||||
def test_colors_usage_by_threshold(self):
|
||||
self.assertEqual([statusline.usage_color(p) for p in (49, 50, 79, 80)], [GREEN, YELLOW, YELLOW, RED])
|
||||
|
||||
def test_humanizes_token_counts(self):
|
||||
self.assertEqual([statusline.humanize_tokens(n) for n in (999, 1000, 999_999, 1_250_000)], ["999", "1k", "999k", "1.2M"])
|
||||
|
||||
def test_counts_a_past_reset_as_zero_left(self):
|
||||
self.assertEqual(statusline.reset_suffix(NOW - 60, NOW, UTC), f" {DIM}0m left (11:59){RESET}")
|
||||
|
||||
|
||||
class Script(unittest.TestCase):
|
||||
def run_script(self, stdin):
|
||||
return subprocess.run([sys.executable, str(pathlib.Path(statusline.__file__))], capture_output=True, env={"HOME": "/nonexistent", "PATH": "/usr/bin:/bin"}, input=stdin, text=True)
|
||||
|
||||
def test_prints_the_status_without_a_trailing_newline(self):
|
||||
ran = self.run_script(json.dumps({"cwd": "/nonexistent/a", "model": {"display_name": "Opus"}}))
|
||||
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, SEP.join([f"{CYAN}~/a{RESET}", f"{DIM}Opus{RESET}"]), ""))
|
||||
|
||||
def test_prints_nothing_for_input_that_is_not_json(self):
|
||||
ran = self.run_script("not json")
|
||||
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, "", ""))
|
||||
|
||||
def test_shows_the_branch_of_the_directory(self):
|
||||
with tempfile.TemporaryDirectory() as checkout:
|
||||
subprocess.run(["git", "init", "-q", "-b", "trunk", checkout], check=True)
|
||||
ran = self.run_script(json.dumps({"cwd": checkout}))
|
||||
self.assertEqual(ran.stdout, SEP.join([f"{CYAN}{checkout}{RESET}", f"{DIM}trunk{RESET}"]))
|
||||
+2
-2
@@ -6,10 +6,10 @@ from test_python_floor import ROOT, readme_floor
|
||||
|
||||
|
||||
class Types(unittest.TestCase):
|
||||
def test_mypy_passes_on_loop_claude_at_the_floor(self):
|
||||
def test_mypy_passes_on_the_tools_at_the_floor(self):
|
||||
floor = readme_floor()
|
||||
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
|
||||
if shutil.which("uv") is None:
|
||||
self.fail("uv on PATH fetches mypy; see README.md's Test line")
|
||||
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
Reference in New Issue
Block a user