autocommit/autocommit/git.py

62 lines
1.9 KiB
Python

import subprocess
from rich.console import Console
from .llm import LLMClient
console = Console()
class GitHandler:
def __init__(self, llm_client=None):
if llm_client:
self.llm_client = llm_client
else:
from .llm import LLMClient
self.llm_client = LLMClient()
def get_diff(self) -> str:
# 使用 subprocess 获取 git diff
try:
result = subprocess.run(
["git", "diff", "--staged"],
capture_output=True,
text=True,
encoding="utf-8",
)
return result.stdout
except FileNotFoundError:
raise Exception("Git 未安装或不在系统路径中")
except Exception as e:
raise Exception(f"获取 Git 差异失败: {e}")
def commit_with_message(self, message: str):
# 使用 git commit -m
try:
result = subprocess.run(
["git", "commit", "-m", message],
capture_output=True,
text=True,
encoding="utf-8",
)
if result.returncode != 0:
raise Exception(f"Git 提交失败: {result.stderr}")
except FileNotFoundError:
raise Exception("Git 未安装或不在系统路径中")
except Exception as e:
raise Exception(f"提交失败: {e}")
def auto_commit(self):
diff = self.get_diff()
if not diff:
print("没有暂存的更改")
console.print("[yellow]⚠️ 没有暂存的更改[/yellow]")
console.print("[cyan]提示: 请先使用 `git add` 暂存文件[/cyan]")
return
message = self.llm_client.generate_commit_message(diff)
if message:
self.commit_with_message(message)
console.print(f"[green]✅ 已提交: {message}[/green]")