用 AI 自动生成 Git Commit Message——告别"fix bug""update"式的提交信息
一个轻量工具:写好代码 git add,然后运行 aicommit,AI 自动读取 staged 的改动,生成规范的 commit message。
项目结构
aicommit/
├── aicommit.py
└── .env
核心代码
#!/usr/bin/env python3
# aicommit.py
import subprocess, sys, os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(
api_key=os.getenv("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com/v1",
)
def get_staged_diff():
"""获取已暂存的文件改动。"""
result = subprocess.run(
["git", "diff", "--cached", "--stat"], capture_output=True, text=True
)
stat = result.stdout.strip()
result = subprocess.run(
["git", "diff", "--cached"], capture_output=True, text=True
)
diff = result.stdout.strip()
if not diff:
print("❌ 没有暂存的改动,请先用 git add")
sys.exit(1)
# 截断过长的 diff
if len(diff) > 8000:
diff = diff[:8000] + "\n... (diff truncated)"
return stat, diff
def generate_commit(stat, diff):
"""AI 生成 commit message。"""
prompt = f"""你是一个代码提交信息生成助手。根据 git diff 生成一条规范的 commit message。
规则:
1. 第一行:type(scope): 简短描述(50 字以内)
2. 空行
3. 详细描述:列出主要改动(可选,如果改动简单可以省略)
type 类型:
- feat: 新功能
- fix: 修复 bug
- refactor: 重构
- perf: 性能优化
- docs: 文档
- style: 格式
- test: 测试
- chore: 构建/工具
## 文件统计
{stat}
## 代码改动
{diff}
请输出 commit message:"""
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}],
temperature=0.2,
max_tokens=300,
)
return resp.choices[0].message.content.strip()
def main():
stat, diff = get_staged_diff()
print(f"📊 分析改动中...")
commit_msg = generate_commit(stat, diff)
print(f"\n{'='*60}")
print("AI 生成的 commit message:")
print(f"{'='*60}")
print(commit_msg)
print(f"{'='*60}")
# 询问是否提交
choice = input("\n是否使用此 message 提交?[Y/n] ").strip().lower()
if choice in ("", "y", "yes"):
subprocess.run(["git", "commit", "-m", commit_msg])
print("✅ 已提交")
if __name__ == "__main__":
main()
使用方式
# 1. 正常开发,改完代码
git add src/api/auth.py src/models/user.py
# 2. 运行 AI commit
python aicommit.py
# 输出:
📊 分析改动中...
============================================================
AI 生成的 commit message:
============================================================
feat(auth): 添加 JWT Token 刷新机制
- 新增 refresh_token 接口
- 修改 Token 过期逻辑,支持滑动过期
- 添加 Token 黑名单检查
============================================================
是否使用此 message 提交?[Y/n]
# 3. 回车确认 → 自动 commit
✅ 已提交
设为 Git 别名
git config --global alias.ac '!python /path/to/aicommit.py'
之后只需要:
git add .
git ac # 一行命令完成 AI commit
成本
一次 commit 约消耗 1000-3000 token,DeepSeek-V4 费用不到 1 分钱。每天提交 5 次,一个月不到 1 块钱。
总结
AI 自动生成 commit message,效果好于手动写的"fix bug""update"——让提交记录真正有意义。
本文由 Zyentor(智元界)原创发布