如何利用 Qwen2.5-Coder 构建一个能自动修复 Bug 的本地 Git Hook 工作流
pre-commit 钩子,能直接在 git commit 阶段拦截低级 Bug,不用等 CI 跑完才发现低级错误。这套方案的核心是利用本地 LLM 的低延迟和零成本,在代码进入暂存区时进行最后一波“语义扫描”。我目前的实现逻辑是:编写一个 Python 脚本作为中间层,在 pre-commit 触发时,提取 git diff 中暂存的变更,喂给 Qwen2.5-Coder,如果 AI 判定存在 Bug 且能给出修复建议,则中断 commit 并提示开发者。
环境配置
本地使用 Ollama 运行 Qwen2.5-Coder,确保 API 接口在 11434 端口开启。安装 pre-commit 框架:
pip install pre-commit核心脚本实现
在项目根目录创建 .git-hooks/ai_fixer.py。关键点在于 Prompt 必须强制 AI 只输出 JSON 格式,否则脚本无法解析是否需要拦截 commit。
import subprocess
import requests
import sys
# 仅检查暂存区的变更
diff = subprocess.check_output(['git', 'diff', '--cached']).decode('utf-8')
if not diff:
sys.exit(0)
prompt = f"""
Analyze the following git diff for potential bugs, logic errors, or security vulnerabilities.
If a bug is found, respond in JSON format: {{"bug": true, "reason": "description", "fix": "suggested code"}}.
If no bug is found, respond: {{"bug": false}}.
Diff:
{diff}
"""
response = requests.post('http://localhost:11434/api/generate',
json={"model": "qwen2.5-coder:32b", "prompt": prompt, "stream": False, "format": "json"})
result = response.json().get('response', '{}')
# 简单的逻辑判断,如果 bug 为 true 则退出码为 1,拦截 commit
if '"bug": true' in result:
print(f"AI Bug Detector: \n{result}")
sys.exit(1)配置 pre-commit 触发
在 .pre-commit-config.yaml 中配置该脚本:
repos:
- repo: local
hooks:
- id: qwen-bug-fixer
name: Qwen2.5 Coder Bug Check
entry: python3 .git-hooks/ai_fixer.py
language: python
stages: [commit]实战踩坑与优化技巧
上下文截断问题:如果一次 commit 的文件太多,git diff 会超出 LLM 的上下文窗口,导致分析失效。建议在脚本中加入文件过滤,只针对 .py 或 .ts 等核心逻辑文件进行扫描,跳过 package-lock.json 或 yarn.lock。
误报率处理:AI 有时会对代码风格(如变量命名)报 Bug。为了避免频繁被拦截导致心烦,我修改了 Prompt,要求它只有在“会导致运行时崩溃或逻辑错误”时才返回 bug: true。
效率提升点:
并发请求:如果项目大,可以把不同文件的 diff 分开并行调用 Ollama API。
自动应用修复:目前的流程是拦截 → 人工改。进阶做法是在脚本中增加 --apply 参数,让 AI 直接通过 git apply 将修复补丁打在本地,但这需要极高的模型信任度,建议初学者先走拦截模式。
全部回复 (0)
还没有回复,来发第一条吧!
