Automatically perform AI review on modified code during git commit
发表于 2025-07-25
git commit时自动对修改代码进行AI review
研发人员经常需要修改,提交代码。但有时会因为粗心,或者疏忽,导致提交的代码存在一些错误或者隐患。如果能有人帮忙review一下,那就太好了。 现在AI发展迅猛,我们可以借用AI来帮我们review代码,消除大部分常见问题,甚至能提出优化建议,使你的代码质量大大提高。
下面我来教大家怎么用git + ChatGPT 来实现git commit时的AI自动review。
1. 获取OPENAI的API key
1.1 创建 API key
打开链接 platform.openai.com/account/api-keys ,登录你的OpenAPI账户。
点击Create new secret key,输入Name,点击创建即可。
创建后记得把key保存备用,记得千万不要暴露在网上,也不要轻易借给他人使用。
1.2 充值账户
因为openai API key是预付费,按token收费,所以我们要先给账户充值。
打开链接 platform.openai.com/settings/organization/billing/overview ,可以看到你的余额。
然后选择充值 Add to credit balance
最低充值$5, 我们添加信用卡账户,确认后充值成功。
2. 安装依赖
在开发机器上,需要安装openai依赖包。
pip install openai
PS:如果需要root权限,记得在命令前加上sudo
3. 编辑pre-commit
cp .git/hooks/pre-commit.sample .git/hooks/pre-commit
vim .git/hooks/pre-commit
pre-commit 已经有了一些基础脚本,可以删除,也可以保留。 我们在后面添加以下脚本内容:
diff=$(git diff --cached --function-context)
if [ -z "$diff" ]; then
echo "No staged changes to review."
exit 0
fi
python3 .git/hooks/ai_review.py "$diff"
exit_code=$?
if [ $exit_code -eq 1 ]; then
echo "Commit aborted due to AI review feedback."
exit 1
fi
这部分主要是生成diff,并调用 ai_review.py 去review 它。
4. 编写ai_review.py 脚本
创建 .git/hooks/ai_review.py 文件,并赋予执行权限
touch .git/hooks/ai_review.py
chmod 777 .git/hooks/ai_review.py
vim .git/hooks/ai_review.py
编辑脚本,写入以下内容
import openai
import sys
import os
diff_text = sys.argv[1] if len(sys.argv) > 1 else ""
if len(diff_text.strip()) == 0:
print("No diff content provided.")
sys.exit(0)
client = openai.OpenAI(
api_key = os.getenv("OPENAI_API_KEY", "paste-your-openai-key-here")
)
prompt = (
"You are a senior code reviewer. Please review the following Git diff and point out:\n"
"- Possible bugs or logic flaws\n"
"- Code quality or best practice issues\n"
"- Suggestions for improvement\n\n"
"Only comment on meaningful issues. Here is the Git diff:\n\n"
"```\n" + diff_text + "\n```"
)
response = client.chat.completions.create(
#model="gpt-3.5-turbo",
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0.2,
)
review = response.choices[0].message.content.strip()
print("\n===== AI Review Summary =====")
print(review)
print("=============================\n")
if "bug" in review.lower() or "issue" in review.lower():
print("⚠️ Potential issues detected. Please review before pushing.")
sys.exit(1)
在 paste-your-openai-key-here 位置粘贴你之前在openai网址获取的openai key字串。
在model这里填入你想使用的模型,”gpt-3.5-turbo性价比更好,gpt-4性能更佳。根据自己的情况做出合适的选择。
5. 测试验证
随便找一段代码,故意在其中添加几行错误代码,然后提交。 观察是否能够给出AI review结果。
$ git commit
===== AI Review Summary =====
1. Possible bugs or logic flaws:
- The line `pr_info("skb->dev:%s\n", skb->dev->name);` is a potential null pointer dereference. `skb` is not initialized before this line, so it could be null, causing a crash when trying to access `skb->dev->name`.
2. Code quality or best practice issues:
- The logging statement `pr_info("skb->dev:%s\n", skb->dev->name);` is not very descriptive. It would be better to provide more context in the log message.
- There is inconsistent spacing around the if statement `if(inet->combo)`. It would be better to have a space after the `if` for readability and consistency with the rest of the code.
3. Suggestions for improvement:
- Move the logging statement `pr_info("skb->dev:%s\n", skb->dev->name);` to after the `skb` is initialized by `skb = skb_recv_datagram(sk, flags, &err);`.
- Add a null check for `skb->dev` before trying to access `skb->dev->name` to prevent potential null pointer dereference.
- Improve the log message to provide more context about what is being logged.
- Add a space after the `if` in `if(inet->combo)` to improve readability and consistency.
=============================
⚠️ Potential issues detected. Please review before pushing.
❌ Commit aborted due to AI review feedback.
看起来还不错,给出错误原因,也给出最优实践,还给出改进建议。
本文访问次数:... 次