|
| 1 | +"""Interactive commit review loop, guardrails, editor handling, and git execution.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import shlex |
| 8 | +import shutil |
| 9 | +import subprocess |
| 10 | +import sys |
| 11 | +import tempfile |
| 12 | +import time |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +from rich.console import Console |
| 16 | +from rich.panel import Panel |
| 17 | + |
| 18 | +from gitmate import config as config_mod |
| 19 | +from gitmate.config import GitmateConfig |
| 20 | +from gitmate.diff_extractor import DiffExtractor, GitCommandError |
| 21 | +from gitmate.fallback import generate_commit_message |
| 22 | +from gitmate.metrics import record_invocation |
| 23 | +from gitmate.providers.base import LLMProvider |
| 24 | +from gitmate.token_budget import TokenCounter |
| 25 | + |
| 26 | +logger = logging.getLogger("gitmate.committer") |
| 27 | + |
| 28 | +GIT_COMMENT_BLOCK = ( |
| 29 | + "\n\n# Please enter the commit message for your changes. Lines starting\n" |
| 30 | + "# with '#' will be ignored, and an empty message aborts the commit.\n" |
| 31 | +) |
| 32 | + |
| 33 | + |
| 34 | +def _safe_record_telemetry( |
| 35 | + command: str, |
| 36 | + model: str, |
| 37 | + tokens_in: int | None, |
| 38 | + tokens_out: int | None, |
| 39 | + cache_hit: bool, |
| 40 | + latency_ms: int | None, |
| 41 | + fallback_used: bool, |
| 42 | +) -> None: |
| 43 | + """Record invocation to metrics database without propagating errors.""" |
| 44 | + try: |
| 45 | + record_invocation( |
| 46 | + command=command, |
| 47 | + model=model, |
| 48 | + tokens_in=tokens_in, |
| 49 | + tokens_out=tokens_out, |
| 50 | + cache_hit=cache_hit, |
| 51 | + latency_ms=latency_ms, |
| 52 | + fallback_used=fallback_used, |
| 53 | + ) |
| 54 | + except Exception as exc: # noqa: BLE001 |
| 55 | + logger.warning("Failed to record telemetry: %s", exc) |
| 56 | + |
| 57 | + |
| 58 | +def _resolve_editor() -> str: |
| 59 | + """Resolve the preferred editor command from environment or fallback.""" |
| 60 | + for var in ("GIT_EDITOR", "VISUAL", "EDITOR"): |
| 61 | + val = os.environ.get(var) |
| 62 | + if val and val.strip(): |
| 63 | + return val.strip() |
| 64 | + if shutil.which("nano"): |
| 65 | + return "nano" |
| 66 | + return "vi" |
| 67 | + |
| 68 | + |
| 69 | +def _render_panel(console: Console, message: str, model: str, is_fallback: bool) -> None: |
| 70 | + """Display the proposed commit message in a styled Rich Panel.""" |
| 71 | + status_badge = ( |
| 72 | + "[yellow bold]⚠ FALLBACK TEMPLATE[/yellow bold]" |
| 73 | + if is_fallback |
| 74 | + else f"[green bold]{model}[/green bold]" |
| 75 | + ) |
| 76 | + panel = Panel( |
| 77 | + message, |
| 78 | + title=f"Proposed Commit Message [dim]({status_badge})[/dim]", |
| 79 | + border_style="yellow" if is_fallback else "green", |
| 80 | + padding=(1, 2), |
| 81 | + expand=False, |
| 82 | + ) |
| 83 | + console.print(panel) |
| 84 | + |
| 85 | + |
| 86 | +def _execute_commit(message: str, console: Console | None = None, cwd: Path | None = None) -> int: |
| 87 | + """Commit using a temporary file with git commit -F, ensuring cleanup in finally.""" |
| 88 | + with tempfile.NamedTemporaryFile( |
| 89 | + mode="w", |
| 90 | + encoding="utf-8", |
| 91 | + prefix="gitmate_commit_", |
| 92 | + delete=False, |
| 93 | + ) as tf: |
| 94 | + tf.write(message) |
| 95 | + tf.flush() |
| 96 | + temp_path = Path(tf.name) |
| 97 | + |
| 98 | + repo_dir = cwd if cwd is not None else Path.cwd() |
| 99 | + try: |
| 100 | + proc = subprocess.run( |
| 101 | + ["git", "commit", "-F", str(temp_path)], |
| 102 | + cwd=repo_dir, |
| 103 | + text=True, |
| 104 | + capture_output=True, |
| 105 | + check=False, |
| 106 | + ) |
| 107 | + if proc.returncode == 0: |
| 108 | + if console is not None and proc.stdout.strip(): |
| 109 | + console.print(proc.stdout.strip()) |
| 110 | + else: |
| 111 | + if console is not None: |
| 112 | + err_msg = proc.stderr.strip() or proc.stdout.strip() |
| 113 | + if err_msg: |
| 114 | + console.print(f"[red]{err_msg}[/red]") |
| 115 | + return proc.returncode |
| 116 | + except FileNotFoundError: |
| 117 | + if console is not None: |
| 118 | + console.print("[red]error:[/red] git binary not found on PATH.") |
| 119 | + return 1 |
| 120 | + finally: |
| 121 | + try: |
| 122 | + if temp_path.exists(): |
| 123 | + temp_path.unlink() |
| 124 | + except OSError: |
| 125 | + pass |
| 126 | + |
| 127 | + |
| 128 | +def _launch_editor( |
| 129 | + initial_message: str, |
| 130 | + console: Console, |
| 131 | + cwd: Path | None = None, |
| 132 | +) -> tuple[bool, str]: |
| 133 | + """Launch user editor pre-populated with message and git comment lines. |
| 134 | +
|
| 135 | + Returns (success, result_message). |
| 136 | + - On non-zero exit code: returns (False, initial_message). |
| 137 | + - On exit code 0: strips '#' comments and whitespace; if empty, returns (True, ""). |
| 138 | + - On exit code 0 with content: returns (True, cleaned_message). |
| 139 | + """ |
| 140 | + content = initial_message.rstrip() + GIT_COMMENT_BLOCK |
| 141 | + with tempfile.NamedTemporaryFile( |
| 142 | + mode="w", |
| 143 | + encoding="utf-8", |
| 144 | + prefix="gitmate_edit_", |
| 145 | + suffix=".txt", |
| 146 | + delete=False, |
| 147 | + ) as tf: |
| 148 | + tf.write(content) |
| 149 | + tf.flush() |
| 150 | + temp_path = Path(tf.name) |
| 151 | + |
| 152 | + editor_cmd = _resolve_editor() |
| 153 | + cmd_parts = shlex.split(editor_cmd) |
| 154 | + repo_dir = cwd if cwd is not None else Path.cwd() |
| 155 | + |
| 156 | + try: |
| 157 | + proc = subprocess.run( |
| 158 | + [*cmd_parts, str(temp_path)], |
| 159 | + cwd=repo_dir, |
| 160 | + check=False, |
| 161 | + ) |
| 162 | + if proc.returncode != 0: |
| 163 | + console.print( |
| 164 | + f"[yellow]Edit aborted by editor (exit code {proc.returncode}). " |
| 165 | + "Keeping existing proposed message.[/yellow]" |
| 166 | + ) |
| 167 | + return False, initial_message |
| 168 | + |
| 169 | + raw_text = temp_path.read_text(encoding="utf-8") |
| 170 | + cleaned_lines = [ |
| 171 | + line.rstrip() for line in raw_text.splitlines() if not line.strip().startswith("#") |
| 172 | + ] |
| 173 | + cleaned_message = "\n".join(cleaned_lines).strip() |
| 174 | + if not cleaned_message: |
| 175 | + console.print("[red]Aborting commit due to empty commit message.[/red]") |
| 176 | + return True, "" |
| 177 | + return True, cleaned_message |
| 178 | + except FileNotFoundError: |
| 179 | + console.print(f"[red]error:[/red] Editor command '{cmd_parts[0]}' not found on PATH.") |
| 180 | + return False, initial_message |
| 181 | + finally: |
| 182 | + try: |
| 183 | + if temp_path.exists(): |
| 184 | + temp_path.unlink() |
| 185 | + except OSError: |
| 186 | + pass |
| 187 | + |
| 188 | + |
| 189 | +def commit_flow( |
| 190 | + yes: bool = False, |
| 191 | + cfg: GitmateConfig | None = None, |
| 192 | + diff_extractor: DiffExtractor | None = None, |
| 193 | + console: Console | None = None, |
| 194 | + provider: LLMProvider | None = None, |
| 195 | + secret_store: config_mod.SecretStore | None = None, |
| 196 | + counter: TokenCounter | None = None, |
| 197 | +) -> int: |
| 198 | + """Execute the commit command review loop. Returns process exit code (0 or 1).""" |
| 199 | + con = console if console is not None else Console() |
| 200 | + active_cfg = cfg if cfg is not None else config_mod.load_config() |
| 201 | + |
| 202 | + extractor = ( |
| 203 | + diff_extractor |
| 204 | + if diff_extractor is not None |
| 205 | + else DiffExtractor(extra_ignores=active_cfg.ignore_globs) |
| 206 | + ) |
| 207 | + repo_dir = extractor._repo |
| 208 | + |
| 209 | + # 1. Staged diff check |
| 210 | + try: |
| 211 | + staged_diffs = extractor.staged() |
| 212 | + except GitCommandError as exc: |
| 213 | + con.print(f"[red]error:[/red] {exc}") |
| 214 | + return 1 |
| 215 | + |
| 216 | + if not staged_diffs: |
| 217 | + con.print("No staged changes to commit. Use 'git add' to stage files first.") |
| 218 | + return 0 |
| 219 | + |
| 220 | + # 2. TTY and non-interactive guardrail checks |
| 221 | + if not sys.stdin.isatty() and not yes: |
| 222 | + con.print( |
| 223 | + "[red]error:[/red] Interactive review requires a TTY terminal. " |
| 224 | + "Use --yes for non-interactive commit (requires 'allow_noninteractive_commit' in config)." |
| 225 | + ) |
| 226 | + return 1 |
| 227 | + |
| 228 | + if yes and not active_cfg.allow_noninteractive_commit: |
| 229 | + con.print( |
| 230 | + "[red]error:[/red] Non-interactive commit (--yes) is disabled by default.\n" |
| 231 | + "To enable, run: gitmate config set allow_noninteractive_commit true" |
| 232 | + ) |
| 233 | + return 1 |
| 234 | + |
| 235 | + active_counter = counter |
| 236 | + if active_counter is None and provider is not None: |
| 237 | + |
| 238 | + class _SimpleCounter(TokenCounter): |
| 239 | + def count_tokens(self, text: str, model: str) -> int: |
| 240 | + return max(1, len(text) // 4) |
| 241 | + |
| 242 | + active_counter = _SimpleCounter() |
| 243 | + |
| 244 | + # 3. Initial generation & telemetry recording |
| 245 | + t0 = time.perf_counter() |
| 246 | + gen_result = generate_commit_message( |
| 247 | + diffs=staged_diffs, |
| 248 | + cfg=active_cfg, |
| 249 | + provider=provider, |
| 250 | + counter=active_counter, |
| 251 | + console=con, |
| 252 | + secret_store=secret_store, |
| 253 | + bypass_cache=False, |
| 254 | + ) |
| 255 | + latency_ms = int((time.perf_counter() - t0) * 1000) |
| 256 | + |
| 257 | + _safe_record_telemetry( |
| 258 | + command="commit", |
| 259 | + model=gen_result.model, |
| 260 | + tokens_in=gen_result.input_tokens, |
| 261 | + tokens_out=gen_result.output_tokens, |
| 262 | + cache_hit=gen_result.cache_hit, |
| 263 | + latency_ms=latency_ms, |
| 264 | + fallback_used=gen_result.is_fallback, |
| 265 | + ) |
| 266 | + |
| 267 | + current_message = gen_result.text |
| 268 | + current_model = gen_result.model |
| 269 | + current_is_fallback = gen_result.is_fallback |
| 270 | + |
| 271 | + # 4. Fast path: --yes with allow_noninteractive_commit enabled |
| 272 | + if yes: |
| 273 | + code = _execute_commit(current_message, console=con, cwd=repo_dir) |
| 274 | + return code |
| 275 | + |
| 276 | + # 5. Interactive review loop |
| 277 | + _render_panel(con, current_message, current_model, current_is_fallback) |
| 278 | + |
| 279 | + while True: |
| 280 | + try: |
| 281 | + raw_input = con.input( |
| 282 | + "[bold cyan]?[/bold cyan] [bold][a]ccept / [e]dit / [r]egenerate / [c]ancel:[/bold] " |
| 283 | + ) |
| 284 | + except (EOFError, KeyboardInterrupt): |
| 285 | + con.print("\nCommit cancelled.") |
| 286 | + return 0 |
| 287 | + |
| 288 | + choice = raw_input.strip().lower() |
| 289 | + if not choice: |
| 290 | + con.print( |
| 291 | + "[yellow]Please select an option: [a]ccept, [e]dit, [r]egenerate, or [c]ancel.[/yellow]" |
| 292 | + ) |
| 293 | + continue |
| 294 | + |
| 295 | + if choice in ("a", "accept"): |
| 296 | + code = _execute_commit(current_message, console=con, cwd=repo_dir) |
| 297 | + return code |
| 298 | + |
| 299 | + elif choice in ("e", "edit"): |
| 300 | + success, edited_msg = _launch_editor(current_message, console=con, cwd=repo_dir) |
| 301 | + if success: |
| 302 | + if not edited_msg: |
| 303 | + return 1 |
| 304 | + current_message = edited_msg |
| 305 | + _render_panel(con, current_message, current_model, current_is_fallback) |
| 306 | + |
| 307 | + elif choice in ("r", "regenerate"): |
| 308 | + con.print("Regenerating commit message with fresh API call...") |
| 309 | + t0 = time.perf_counter() |
| 310 | + gen_result = generate_commit_message( |
| 311 | + diffs=staged_diffs, |
| 312 | + cfg=active_cfg, |
| 313 | + provider=provider, |
| 314 | + counter=active_counter, |
| 315 | + console=con, |
| 316 | + secret_store=secret_store, |
| 317 | + bypass_cache=True, |
| 318 | + ) |
| 319 | + latency_ms = int((time.perf_counter() - t0) * 1000) |
| 320 | + |
| 321 | + _safe_record_telemetry( |
| 322 | + command="commit", |
| 323 | + model=gen_result.model, |
| 324 | + tokens_in=gen_result.input_tokens, |
| 325 | + tokens_out=gen_result.output_tokens, |
| 326 | + cache_hit=False, |
| 327 | + latency_ms=latency_ms, |
| 328 | + fallback_used=gen_result.is_fallback, |
| 329 | + ) |
| 330 | + |
| 331 | + current_message = gen_result.text |
| 332 | + current_model = gen_result.model |
| 333 | + current_is_fallback = gen_result.is_fallback |
| 334 | + _render_panel(con, current_message, current_model, current_is_fallback) |
| 335 | + |
| 336 | + elif choice in ("c", "cancel"): |
| 337 | + con.print("Commit cancelled.") |
| 338 | + return 0 |
| 339 | + |
| 340 | + else: |
| 341 | + con.print( |
| 342 | + f"[yellow]Invalid selection '{raw_input}'. " |
| 343 | + "Please choose [a]ccept, [e]dit, [r]egenerate, or [c]ancel.[/yellow]" |
| 344 | + ) |
0 commit comments