使用 Git 提交 Patch 并发送邮件
在 Linux 内核社区或其他开源项目中,git send-email
是最常用的提交补丁工具之一。它能将补丁以标准格式发送到邮件列表和维护者手中。
环境准备
安装 Git 及发送邮件工具:
sudo apt-get install git git-email
配置 .gitconfig
编辑 ~/.gitconfig
,配置用户信息和邮件服务:
[user]
name = Your Name
email = you@example.com
[sendemail]
smtpencryption = tls
smtpserver = smtp.gmail.com
smtpuser = you@gmail.com
smtpserverport = 587
chainreplyto = false
💡 使用 Gmail 时,建议配置 应用专用密码,而不是主账号密码。
准备 Patch
-
清理代码(可选)
在提交之前,可以运行清理脚本:
./script/cleanfile foo.c
-
提交修改
git add foo.c git commit -s -m "foo: fix memory leak"
-s
选项会自动添加Signed-off-by
,这是内核提交的要求。 -
生成补丁
git format-patch -n --cover-letter
-n
表示生成最近n
次提交的补丁。--cover-letter
会生成一封总述邮件(可编辑补丁集说明)。-
推荐格式:
git format-patch -n -s --cover-letter \ --subject-prefix="PATCH v2"
检查 Patch
-
运行内核脚本检查补丁风格
./scripts/checkpatch.pl 0001-fix-bug.patch
-
找到维护者
./scripts/get_maintainer.pl 0001-fix-bug.patch
这会告诉你该补丁应该发送给谁。
发送补丁
使用 git send-email
:
git send-email 0001-fix-bug.patch \
--to maintainer@example.com \
--cc reviewer@example.com
- 使用
--annotate
可以在发送前逐个编辑补丁邮件。 - 编辑完成后,在 Vim 中用
:wn
保存并进入下一个补丁,最后一个用:wq
。
使用 --identity
管理不同配置
如果经常给固定邮件组发补丁,可以在 .gitconfig
添加自定义配置:
[sendemail "lkml"]
smtpserver = smtp.gmail.com
smtpuser = you@gmail.com
smtpencryption = tls
smtpserverport = 587
chainreplyto = false
to = linux-kernel@vger.kernel.org
cc = maintainer@example.com, reviewer@example.com
然后直接执行:
git send-email --identity=lkml *.patch
配置 Git Hooks 发送 Commit 通知
有时我们希望 Git Server 自动发送提交通知邮件,这可以通过 Git hooks 实现。
什么是 Git Hook?
Git hook 是在特定事件触发时执行的脚本。例如,当有用户 push 到仓库时,可以通过 post-receive
hook 自动发送通知邮件。
默认 hooks 在 .git/hooks/
下,若要修改位置,可以设置:
git config core.hooksPath /path/to/hooks
文档参考:Git Hooks
配置步骤
-
设置邮件参数
编辑 Git Server 仓库的
.git/config
:[hooks] showrev = "git show -C %s; echo" emailprefix = "[MyProject] " mailinglist = dev@example.com,review@example.com envelopesender = git@example.com
-
修改项目名称
为了在邮件里显示项目名,编辑
.git/description
:my-cool-project
未修改时,邮件主题会显示 UNNAMED PROJECT。 修改后主题类似:
[MyProject] my-cool-project branch master updated. [SHA1]
-
启用 hook
在
.git/hooks/
下将post-receive.sample
改名为post-receive
并赋予可执行权限:mv .git/hooks/post-receive.sample .git/hooks/post-receive chmod +x .git/hooks/post-receive
总结
- 使用
git format-patch
+git send-email
是 Linux 内核社区的标准流程。 - 在提交前务必使用
checkpatch.pl
和get_maintainer.pl
。 - 通过
.gitconfig
的--identity
可以高效管理不同邮件配置。 - Git hooks 可以实现提交通知,方便团队协作。
`