根据每次提交的 代码 diff,调用 OpenAI 兼容 的大模型 API,自动生成更清晰的提交说明,并用 git filter-branch 重写 Git 历史中的 commit message。
适合把历史上大量「update」「fix」这类敷衍说明,批量改成可读、可追溯的说明(会改写 SHA,已推送分支需协调后强推)。
- 遍历指定引用可达的提交(可选处理所有引用上的提交)
- 将旧标题/正文 + unified diff 发给 Chat Completions API
- 失败时打印 HTTP 状态与响应体(便于排查模型名、限流、上下文过长等)
--dry-run仅预览新说明,不修改仓库
- Python 3.10+
- 已
git init的仓库 - 任意提供
/v1/chat/completions的 API(OpenAI、Azure OpenAI、SiliconFlow 等)
git clone <本仓库地址>
cd git_commit_message_cleaner
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install .安装后可用:
git-commit-message-cleaner rewrite --help也可不激活虚拟环境,直接调用:
/path/to/git_commit_message_cleaner/.venv/bin/git-commit-message-cleaner rewrite --help全局安装(可选,需已安装 pipx):
pipx install /path/to/git_commit_message_cleaner说明: 在部分环境下
pip install -e .(可编辑安装)可能因 Python 对.pth文件的限制导致找不到包;若遇ModuleNotFoundError,请改用pip install .。
不要把 API Key 写进仓库。推荐使用环境变量:
export OPENAI_API_KEY="你的密钥"也可使用 --api-key(可能进入 shell 历史,不推荐)。
仅预览(推荐先跑):
git-commit-message-cleaner rewrite --repo /path/to/your/repo --dry-run真正改写历史:
git-commit-message-cleaner rewrite --repo /path/to/your/repo在仓库目录内且 --repo 默认为当前目录时:
cd /path/to/your/repo
git-commit-message-cleaner rewrite --dry-run
git-commit-message-cleaner rewrite第三方兼容接口(以 SiliconFlow 为例):
export OPENAI_API_KEY="你的密钥"
git-commit-message-cleaner rewrite --repo . \
--base-url https://api.siliconflow.cn/v1 \
--model "Qwen/Qwen3-Omni-30B-A3B-Instruct"模型 ID 须与服务商控制台完全一致。
| 参数 | 说明 |
|---|---|
--repo |
目标 Git 仓库路径(默认:.) |
--api-key |
API 密钥(默认读取 OPENAI_API_KEY) |
--base-url |
API 根地址,默认 https://api.openai.com/v1 |
--model |
模型名,默认 gpt-4o-mini |
--timeout |
单次请求超时(秒),默认 120 |
--ref |
重写该引用可达的历史,默认 HEAD |
--refs |
head:仅 --ref;all:等价于对所有引用执行 filter-branch --all |
--max-diff-bytes |
diff 超过该 UTF-8 字节数则截断,默认 120000 |
--dry-run |
只打印建议的 message,不写历史 |
成本提示: 每个提交会发起 一次 LLM 请求,提交多时请注意费用与耗时。
- 改写已推送历史 后,需要使用
git push --force-with-lease(或与团队约定的方式),并通知协作者。 - 使用
git filter-branch;Git 可能在refs/original/留下备份引用,可按 官方文档 在确认无误后清理。 - 合并提交 当前按与第一父提交之间的 diff 生成说明,复杂 merge 的概括可能较粗。
- 务必备份仓库(复制目录或额外 clone)再执行非
--dry-run的改写。
git_commit_message_cleaner/
├── pyproject.toml
├── README.md
└── src/git_commit_message_cleaner/
├── cli.py # 命令行与 filter-branch 调用
├── git_ops.py # git 命令封装
└── llm.py # HTTP 调用与错误信息解析
- httpx(HTTP 客户端)
若你发现 API 报错信息仍不够,欢迎提 Issue;也欢迎 PR 改进 prompt 或增加只改写「短标题」等过滤策略。