🤖 用 AI 写 Git Commit Message?我让新手秒变 Git 高手!

167 阅读4分钟

“你的 commit message 又写成 fix bug 了?”
“别骂了,我这就去改……”

如果你也曾因提交信息太随意被 Leader 点名批评,或者看着别人优雅的 Git 日志自叹不如——那么恭喜你,今天这篇文章就是为你量身打造的「Git 提交信息拯救计划」!

我们将一起搭建一个 全栈 AI Git Commit Message 生成器,让你每次 git commit 都像 Linus 本人在敲键盘 ✨。


🧠 为什么 Git 提交信息这么重要?

很多人觉得:“代码能跑就行,commit message 随便写写呗。”
但现实很骨感:

  • 项目日志混乱:三个月后回看 update file,你根本不知道改了啥。
  • Code Review 困难:Reviewer 看不懂你意图,只能反复问“这是干啥的?”
  • 绩效考核吃亏:Leader 翻 Git 历史时,看到一串 fix, add, ok,心里默默给你打了个 ❌。
  • 团队协作灾难:新人接手项目,光看 commit log 就想辞职。

规范的 commit message = 专业开发者的第一张名片 💼

而今天,我们要做的,就是让 AI 来帮你写规范、清晰、符合 Conventional Commits 的提交信息


🛠️ 技术栈:全栈 + AI,三端联动

我们的小神器由三部分组成,堪称“三位一体”:

模块技术职责
前端React + Tailwind CSS + Axios用户界面,展示 AI 生成的 commit message
后端Node.js + Express接收请求,调用 AI 模型
AI 引擎Ollama + DeepSeek-R1:8B(本地 GPU 运行)真正的“大脑”,理解代码差异并生成高质量 commit

无需联网!无需 OpenAI API!全部跑在你自己的电脑上,隐私安全拉满 🔒


🌐 架构图:数据如何流动?

[前端浏览器] 
    ↓ (POST /chat)
[Express 后端 @3000]
    ↓ (调用 Ollama API)
[Ollama AI @11434 → DeepSeek-R1:8B]
    ↑ (返回 commit message)
[Express 返回 JSON][前端展示结果]

整个过程不到 5 秒,AI 就能根据你的 git diff 输出一条像模像样的 commit:

✅ feat(auth): implement JWT token refresh logic
✅ fix(ui): resolve button overflow on mobile view
✅ docs(readme): update installation instructions

是不是瞬间高大上了?


🧪 后端:Express 的优雅之道

我们用 Express 搭建了一个极简但健壮的 API 服务:

app.post('/chat', async (req, res) => {
  const { message } = req.body;
  if (!message || typeof message !== 'string') {
    return res.status(400).json({ error: "message 必填,必须是字符串" });
  }

  try {
    const prompt = ChatPromptTemplate.fromMessages([
      ['system', '你是一个专业的 Git 提交信息助手,请根据以下代码变更生成符合 Conventional Commits 规范的提交信息。'],
      ['human', '{input}']
    ]);

    const chain = prompt.pipe(model).pipe(new StringOutputParser());
    const result = await chain.invoke({ input: message });

    res.json({ reply: result });
  } catch (e) {
    console.error(e);
    res.status(500).json({ error: "调用大模型失败" });
  }
});

关键点:

  • 输入校验:防止前端乱传数据
  • 错误处理:500 错误不崩服
  • 提示词工程:明确告诉 AI “你要干啥”
  • LangChain 链式调用:模块化、可扩展

Express 虽老,但稳如老狗。配合 cors()express.json() 中间件,跨域和 JSON 解析一键搞定。


🎨 前端:React Hook 封装副作用

我们用自定义 Hook useGitDiff 把 AI 调用逻辑抽离出来:

export const useGitDiff = () => {
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    (async () => {
      setLoading(true);
      const { data } = await chat('请根据以下 git diff 生成 commit message...');
      setContent(data.reply);
      setLoading(false);
    })();
  }, []);

  return { loading, content };
};

组件只需关注 UI:

export default function App() {
  const { loading, content } = useGitDiff();
  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-50">
      {loading ? (
        <p className="text-lg">🧠 AI 正在思考中...</p>
      ) : (
        <pre className="bg-white p-4 rounded shadow-md max-w-2xl">{content}</pre>
      )}
    </div>
  );
}

Tailwind 让样式开发快如闪电,Axios 封装统一 API 调用,清爽又高效!


🤯 跨域?不存在的!

前端跑在 http://localhost:5173,后端在 http://localhost:3000 —— 端口不同,浏览器直接 block 请求。

解决方案?一行代码:

app.use(cors());

CORS 就像给前端办了“外交护照”,浏览器一看:“哦,后端特批了,放行!” 🛂


🧪 如何测试?Apifox 来助阵!

开发时用 ApifoxPostman 直接 POST 到 /chat

{
  "message": "diff --git a/src/App.js b/src/App.js\n+ console.log('hello AI');"
}

秒回:

{ "reply": "feat(app): add debug log in App component" }

调试效率翻倍!


🚀 未来展望:不止于 Commit Message

这个小项目其实是个“AI 开发助手”的雏形。下一步我们可以:

  • 自动读取本地 git diff(通过 Electron 或 CLI 工具)
  • 支持多语言模型切换(Qwen、Llama3、DeepSeek)
  • 集成到 VS Code 插件,一键生成 commit
  • 甚至自动 git commit -m "$(ai-commit)"

💡 结语:让 AI 成为你的编程副驾驶

我们不是要取代开发者,而是把重复、枯燥、容易出错的工作交给 AI,让我们专注在真正有创造力的部分。

一个好的 commit message,不仅是对代码的尊重,更是对团队、对未来的自己负责。

现在,你只需要复制粘贴 AI 生成的内容,就能写出让人眼前一亮的 Git 提交记录——
从此,你的 Git 历史,也能登上“最佳实践”榜单!