You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让git commit自动提议子模块的最新提交消息?

让Git自动生成子模块更新的提交消息

方法1:用Git钩子自动生成提交消息

Git的prepare-commit-msg钩子可以在打开提交消息编辑器前自动修改内容,正好用来插入子模块的更新信息。

  1. 在目标仓库(比如foo或myproject)的.git/hooks目录下,创建可执行文件prepare-commit-msg:
#!/bin/sh
# 检测是否有子模块相关的更新
if git diff --cached --name-only | grep -q "\.gitmodules\|modules/" || git diff-tree --cached --name-only HEAD | grep -q "\.gitmodules\|modules/"; then
    # 获取暂存区中子模块的更新摘要(含提交哈希和消息)
    SUBMODULE_SUMMARY=$(git submodule summary --cached)
    # 如果有更新内容,替换默认提交消息
    if [ -n "$SUBMODULE_SUMMARY" ]; then
        echo "Update submodules:" > "$1"
        echo "" >> "$1"
        echo "$SUBMODULE_SUMMARY" >> "$1"
    fi
fi
  1. 给文件添加执行权限:
chmod +x .git/hooks/prepare-commit-msg

之后更新子模块并暂存(比如git add bar),执行git commit时,Git会自动生成类似这样的提交消息:

Update submodules:

* bar abc1234...def5678 (1):
  > Fix null pointer exception in bar's core function

方法2:一键提交带子模块消息的更新

如果不想用钩子,也可以直接用命令生成提交消息并提交,还能做成Git别名简化操作:

直接执行命令

git commit -m "$(echo "Update submodules:" && echo && git submodule summary --cached)"

配置Git别名

编辑你的~/.gitconfig文件,添加:

[alias]
    submod-commit = !git commit -m \"$(echo \"Update submodules:\" && echo && git submodule summary --cached)\"

之后更新子模块并暂存后,直接运行:

git submod-commit

注意事项

  • 钩子是仓库级别的,需要在foo和myproject各自的仓库里分别设置,或者把钩子文件放到公共路径用符号链接引用。
  • 必须先暂存子模块的更新(git add <子模块名>),git submodule summary --cached才能获取到更新信息。
  • 可以根据需求修改钩子或命令里的消息格式,比如改成Update bar to latest commit:加上具体提交内容。

内容的提问来源于stack exchange,提问作者ceremcem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:06:32