|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +from datetime import datetime, timezone |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | + |
| 11 | +DEFAULT_DIGEST_PATH = Path( |
| 12 | + os.environ.get( |
| 13 | + "MY_OPENCODE_DIGEST_PATH", "~/.config/opencode/digests/last-session.json" |
| 14 | + ) |
| 15 | +).expanduser() |
| 16 | + |
| 17 | + |
| 18 | +def now_iso() -> str: |
| 19 | + return datetime.now(timezone.utc).isoformat() |
| 20 | + |
| 21 | + |
| 22 | +def run_text(command: list[str]) -> str: |
| 23 | + try: |
| 24 | + result = subprocess.run( |
| 25 | + command, |
| 26 | + capture_output=True, |
| 27 | + text=True, |
| 28 | + check=False, |
| 29 | + ) |
| 30 | + except Exception: |
| 31 | + return "" |
| 32 | + if result.returncode != 0: |
| 33 | + return "" |
| 34 | + return result.stdout.strip() |
| 35 | + |
| 36 | + |
| 37 | +def collect_git_snapshot(cwd: Path) -> dict: |
| 38 | + branch = run_text(["git", "-C", str(cwd), "branch", "--show-current"]) |
| 39 | + status = run_text(["git", "-C", str(cwd), "status", "--short"]) |
| 40 | + ahead_behind = run_text(["git", "-C", str(cwd), "status", "--short", "--branch"]) |
| 41 | + |
| 42 | + status_lines = [line for line in status.splitlines() if line.strip()] |
| 43 | + return { |
| 44 | + "branch": branch or None, |
| 45 | + "status_count": len(status_lines), |
| 46 | + "status_preview": status_lines[:20], |
| 47 | + "branch_header": ahead_behind.splitlines()[0] if ahead_behind else None, |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | +def build_digest(reason: str, cwd: Path) -> dict: |
| 52 | + return { |
| 53 | + "timestamp": now_iso(), |
| 54 | + "reason": reason, |
| 55 | + "cwd": str(cwd), |
| 56 | + "git": collect_git_snapshot(cwd), |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | +def write_digest(path: Path, digest: dict) -> None: |
| 61 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 62 | + path.write_text(json.dumps(digest, indent=2) + "\n", encoding="utf-8") |
| 63 | + |
| 64 | + |
| 65 | +def run_hook(command: str, digest_path: Path) -> int: |
| 66 | + env = os.environ.copy() |
| 67 | + env["MY_OPENCODE_DIGEST_PATH"] = str(digest_path) |
| 68 | + result = subprocess.run(command, shell=True, env=env, check=False) |
| 69 | + return result.returncode |
| 70 | + |
| 71 | + |
| 72 | +def print_summary(path: Path, digest: dict) -> None: |
| 73 | + print(f"digest: {path}") |
| 74 | + print(f"timestamp: {digest.get('timestamp')}") |
| 75 | + print(f"reason: {digest.get('reason')}") |
| 76 | + print(f"cwd: {digest.get('cwd')}") |
| 77 | + git = digest.get("git", {}) if isinstance(digest.get("git"), dict) else {} |
| 78 | + print(f"branch: {git.get('branch')}") |
| 79 | + print(f"changes: {git.get('status_count')}") |
| 80 | + |
| 81 | + |
| 82 | +def usage() -> int: |
| 83 | + print( |
| 84 | + 'usage: /digest run [--reason <idle|exit|manual>] [--path <digest.json>] [--hook "command"] | /digest show [--path <digest.json>]' |
| 85 | + ) |
| 86 | + return 2 |
| 87 | + |
| 88 | + |
| 89 | +def parse_option(argv: list[str], name: str) -> str | None: |
| 90 | + if name not in argv: |
| 91 | + return None |
| 92 | + index = argv.index(name) |
| 93 | + if index + 1 >= len(argv): |
| 94 | + return None |
| 95 | + return argv[index + 1] |
| 96 | + |
| 97 | + |
| 98 | +def command_run(argv: list[str]) -> int: |
| 99 | + reason = parse_option(argv, "--reason") or "manual" |
| 100 | + path_value = parse_option(argv, "--path") |
| 101 | + hook_value = parse_option(argv, "--hook") |
| 102 | + |
| 103 | + path = Path(path_value).expanduser() if path_value else DEFAULT_DIGEST_PATH |
| 104 | + cwd = Path.cwd() |
| 105 | + |
| 106 | + digest = build_digest(reason=reason, cwd=cwd) |
| 107 | + write_digest(path, digest) |
| 108 | + print_summary(path, digest) |
| 109 | + |
| 110 | + if hook_value: |
| 111 | + code = run_hook(hook_value, path) |
| 112 | + print(f"hook: exited with code {code}") |
| 113 | + return code |
| 114 | + |
| 115 | + return 0 |
| 116 | + |
| 117 | + |
| 118 | +def command_show(argv: list[str]) -> int: |
| 119 | + path_value = parse_option(argv, "--path") |
| 120 | + path = Path(path_value).expanduser() if path_value else DEFAULT_DIGEST_PATH |
| 121 | + if not path.exists(): |
| 122 | + print(f"error: digest file not found: {path}") |
| 123 | + return 1 |
| 124 | + |
| 125 | + digest = json.loads(path.read_text(encoding="utf-8")) |
| 126 | + print_summary(path, digest) |
| 127 | + |
| 128 | + preview = digest.get("git", {}).get("status_preview", []) |
| 129 | + if preview: |
| 130 | + print("status preview:") |
| 131 | + for line in preview: |
| 132 | + print(f"- {line}") |
| 133 | + return 0 |
| 134 | + |
| 135 | + |
| 136 | +def main(argv: list[str]) -> int: |
| 137 | + if not argv: |
| 138 | + return usage() |
| 139 | + |
| 140 | + command = argv[0] |
| 141 | + rest = argv[1:] |
| 142 | + |
| 143 | + if command == "help": |
| 144 | + return usage() |
| 145 | + if command == "run": |
| 146 | + return command_run(rest) |
| 147 | + if command == "show": |
| 148 | + return command_show(rest) |
| 149 | + return usage() |
| 150 | + |
| 151 | + |
| 152 | +if __name__ == "__main__": |
| 153 | + try: |
| 154 | + raise SystemExit(main(sys.argv[1:])) |
| 155 | + except Exception as exc: |
| 156 | + print(f"error: {exc}") |
| 157 | + raise SystemExit(1) |
0 commit comments