Answer the architecture pass's first round
This commit is contained in:
+67
-35
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
import dataclasses
|
||||
import datetime
|
||||
import json
|
||||
import math
|
||||
@@ -6,7 +7,6 @@ import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
CYAN = "\033[36m"
|
||||
DIM = "\033[2m"
|
||||
@@ -16,26 +16,59 @@ RESET = "\033[0m"
|
||||
YELLOW = "\033[33m"
|
||||
|
||||
|
||||
def field(status: object, *path: str) -> object:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Limit:
|
||||
percent: float
|
||||
resets_at: float | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Status:
|
||||
context_percent: float | None
|
||||
context_size: float | None
|
||||
context_used: float | None
|
||||
directory: str
|
||||
five_hour: Limit | None
|
||||
model: str
|
||||
seven_day: Limit | None
|
||||
|
||||
|
||||
def field(raw: object, *path: str) -> object:
|
||||
for key in path:
|
||||
if not isinstance(status, dict):
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
status = status.get(key)
|
||||
return status
|
||||
raw = raw.get(key)
|
||||
return raw
|
||||
|
||||
|
||||
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 number(raw: object, *path: str) -> float | None:
|
||||
found = field(raw, *path)
|
||||
if isinstance(found, bool) or not isinstance(found, (int, float)):
|
||||
return None
|
||||
return found if isinstance(found, int) or math.isfinite(found) else None
|
||||
|
||||
|
||||
def text(status: object, *path: str) -> str:
|
||||
found = field(status, *path)
|
||||
def text(raw: object, *path: str) -> str:
|
||||
found = field(raw, *path)
|
||||
return found if isinstance(found, str) else ""
|
||||
|
||||
|
||||
def directory(status: object) -> str:
|
||||
return text(status, "workspace", "current_dir") or text(status, "cwd")
|
||||
def limit(raw: object, window: str) -> Limit | None:
|
||||
percent = number(raw, "rate_limits", window, "used_percentage")
|
||||
return None if percent is None else Limit(percent, number(raw, "rate_limits", window, "resets_at"))
|
||||
|
||||
|
||||
# The input's fields: https://code.claude.com/docs/en/statusline
|
||||
def parse(raw: object) -> Status:
|
||||
return Status(
|
||||
context_percent=number(raw, "context_window", "used_percentage"),
|
||||
context_size=number(raw, "context_window", "context_window_size"),
|
||||
context_used=number(raw, "context_window", "total_input_tokens"),
|
||||
directory=text(raw, "workspace", "current_dir") or text(raw, "cwd"),
|
||||
five_hour=limit(raw, "five_hour"),
|
||||
model=text(raw, "model", "display_name"),
|
||||
seven_day=limit(raw, "seven_day"),
|
||||
)
|
||||
|
||||
|
||||
def usage_color(percent: int) -> str:
|
||||
@@ -51,7 +84,10 @@ def humanize_tokens(count: int) -> str:
|
||||
|
||||
|
||||
def reset_suffix(epoch: float, now: int, zone: datetime.tzinfo | None) -> str:
|
||||
at = datetime.datetime.fromtimestamp(round(epoch), zone)
|
||||
try:
|
||||
at = datetime.datetime.fromtimestamp(round(epoch), zone)
|
||||
except (OSError, OverflowError, ValueError):
|
||||
return ""
|
||||
seconds = max(0, round(epoch) - now)
|
||||
if seconds >= 86400:
|
||||
left = f"{seconds // 86400}d{seconds % 86400 // 3600}h"
|
||||
@@ -63,39 +99,35 @@ def reset_suffix(epoch: float, now: int, zone: datetime.tzinfo | None) -> str:
|
||||
return f" {DIM}{left} left ({clock}){RESET}"
|
||||
|
||||
|
||||
def usage(label: str, percent: float, suffix: str) -> str:
|
||||
def usage_segment(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:
|
||||
def limit_segment(label: str, window: Limit | None, now: int, zone: datetime.tzinfo | None) -> list[str]:
|
||||
if window 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))]
|
||||
return [usage_segment(label, window.percent, "" if window.resets_at is None else reset_suffix(window.resets_at, now, zone))]
|
||||
|
||||
|
||||
def render(status: object, branch: str, home: str, now: int, zone: datetime.tzinfo | None) -> str:
|
||||
def render(status: Status, branch: str, home: str, now: int, zone: datetime.tzinfo | None) -> str:
|
||||
where = []
|
||||
shown = directory(status)
|
||||
if shown:
|
||||
if status.directory:
|
||||
shown = status.directory
|
||||
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}")
|
||||
if status.model:
|
||||
where.append(f"{DIM}{status.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")
|
||||
if status.context_percent is not None:
|
||||
used, size = status.context_used, status.context_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)
|
||||
load.append(usage_segment("ctx", status.context_percent, tokens))
|
||||
load += limit_segment("5h", status.five_hour, now, zone) + limit_segment("7d", status.seven_day, now, zone)
|
||||
|
||||
return "\n".join(f"{DIM} | {RESET}".join(row) for row in (where, load) if row)
|
||||
|
||||
@@ -110,13 +142,13 @@ def current_branch(where: str) -> str:
|
||||
return found.stdout.strip() if found.returncode == 0 else ""
|
||||
|
||||
|
||||
def main(stdin: typing.TextIO, env: typing.Mapping[str, str]) -> str:
|
||||
def main() -> str:
|
||||
try:
|
||||
status = json.load(stdin)
|
||||
status = parse(json.load(sys.stdin))
|
||||
except ValueError:
|
||||
status = None
|
||||
return render(status, current_branch(directory(status)), env.get("HOME", ""), int(time.time()), None)
|
||||
return f"{RED}warning: statusline.py could not parse its input as JSON{RESET}"
|
||||
return render(status, current_branch(status.directory), os.environ.get("HOME", ""), int(time.time()), None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.write(main(sys.stdin, os.environ))
|
||||
sys.stdout.write(main())
|
||||
|
||||
+15
-5
@@ -1,5 +1,6 @@
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -17,7 +18,7 @@ UTC = datetime.timezone.utc
|
||||
|
||||
|
||||
def render(status, branch="", home="/home/me"):
|
||||
return statusline.render(status, branch, home, NOW, UTC)
|
||||
return statusline.render(statusline.parse(status), branch, home, NOW, UTC)
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
@@ -37,10 +38,15 @@ class Render(unittest.TestCase):
|
||||
]),
|
||||
]))
|
||||
|
||||
def test_shows_nothing_for_an_empty_or_unparsed_status(self):
|
||||
def test_shows_nothing_for_an_empty_status(self):
|
||||
self.assertEqual(render({}), "")
|
||||
self.assertEqual(render([]), "")
|
||||
self.assertEqual(render(None), "")
|
||||
|
||||
def test_skips_infinity_and_keeps_an_integer_too_big_for_a_float(self):
|
||||
self.assertEqual(render({"context_window": {"used_percentage": float("inf")}}), "")
|
||||
self.assertEqual(render({"context_window": {"used_percentage": 10**400}}), f"{DIM}ctx{RESET} {RED}{10**400}%{RESET}")
|
||||
|
||||
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), "")
|
||||
@@ -66,21 +72,25 @@ class Render(unittest.TestCase):
|
||||
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_omits_a_reset_out_of_the_clocks_range(self):
|
||||
self.assertEqual(render({"rate_limits": {"seven_day": {"resets_at": 1790618085238, "used_percentage": 1}}}), f"{DIM}7d{RESET} {GREEN}1%{RESET}")
|
||||
self.assertEqual(render({"rate_limits": {"seven_day": {"resets_at": 1e20, "used_percentage": 1}}}), f"{DIM}7d{RESET} {GREEN}1%{RESET}")
|
||||
|
||||
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)
|
||||
return subprocess.run([statusline.__file__], capture_output=True, env={"HOME": "/nonexistent", "PATH": os.environ["PATH"]}, 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):
|
||||
def test_warns_on_the_status_line_for_input_that_is_not_json(self):
|
||||
ran = self.run_script("not json")
|
||||
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, "", ""))
|
||||
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, f"{RED}warning: statusline.py could not parse its input as JSON{RESET}", ""))
|
||||
|
||||
def test_shows_the_branch_of_the_directory(self):
|
||||
with tempfile.TemporaryDirectory() as checkout:
|
||||
|
||||
Reference in New Issue
Block a user