Git 中的 notes 给提交添加注释

FreeGuideOnline 最新 2026-07-07

bash git notes add


如果省略 `<commit>`,默认就是 `HEAD`。输入内容后保存退出,notes 即被创建。

**示例**:给当前 HEAD 添加一条 note。

```bash
git notes add
# 在编辑器中输入:这个提交修复了登录页面的内存泄漏

为特定提交添加注释

指定提交哈希即可:

git notes add 1a2b3c4

如果你已经有一个消息文件,可以用 -m-F 参数快速添加:

git notes add -m "简单的一句话注释"
git notes add -F review.txt

提示:-m 可以多次使用,消息将会被拼接换行。

查看 Notes

使用 git log 显示

默认的 git log 不显示 notes。需要加上 --notes 选项,它会将 notes 内容显示在对应提交的下方。

git log --notes

输出示例:

commit a1b2c3d4e5f678...
Author: Alice <alice@example.com>
Date:   ...

    修复登录令牌刷新问题

Notes:
    这个提交修复了登录页面的内存泄漏

如果只想查看某个提交的 notes,使用:

git log --notes -1 <commit>

直接查看 Notes 内容

使用 git notes show 命令直接显示某个提交的 notes:

git notes show <commit>

不加参数则显示 HEAD 的 notes。该命令还可以用 --revision 查看不同引用下的 notes(后面会提到)。

共享和推送 Notes

Notes 默认存储在本地引用 refs/notes/commits 中,不会随 git push 自动推送。你需要显式推送 notes 引用:

git push origin refs/notes/commits

为了简化,经常为这个引用设置一个别名推送。或者使用:

git push origin refs/notes/*

这会将所有本地 notes 引用推送到远程。

拉取他人的 Notes

当其他人推送了 notes,你拉取时也需要指定引用:

git fetch origin refs/notes/commits

或在 git fetch 时一次性拉取所有引用(包括 notes):

git fetch --prune-tags origin "+refs/notes/*:refs/notes/*"

更好的做法是在 .git/config 或全局配置中增加 fetch 规则,使 notes 自动随 git fetch 获取:

git config --add remote.origin.fetch "+refs/notes/commits:refs/notes/commits"

此后普通的 git pullgit fetch 都会自动同步 notes。

修改和删除 Notes

修改已有的笔记

使用 git notes edit 命令可以重新打开编辑器,修改已有 note:

git notes edit HEAD

也可以通过 -m 直接覆盖:

git notes add -f -m "新的注释内容" HEAD

-f 表示强制覆盖已存在的 note。

删除笔记

使用 git notes remove 命令删除某提交的 notes:

git notes remove HEAD

删除操作实际上将 notes 引用中的对应条目移除,并不会删除提交本身。

Notes 的命名空间与高级用法

Git Notes 支持多个命名空间,默认使用的是 commits(引用 refs/notes/commits)。你可以创建自定义的命名空间来存储不同类别的注释。

例如,创建一个专门存放代码审查结果的 notes 引用:

git notes --ref=code-review add -m "审查通过,性能良好" HEAD

这条命令会创建引用 refs/notes/code-review,并且 notes 内容只存在于该命名空间下。

查看自定义命名的 notes:

git notes --ref=code-review show HEAD
git log --notes=code-review

命名空间可以完全分离,互不干扰,这为团队合作提供了极大的灵活性。比如:

  • refs/notes/build-status:CI 构建状态
  • refs/notes/issues:关联的问题追踪 ID
  • refs/notes/deploy:记录部署信息

在推送和拉取时,也需要指定相应的引用:

git push origin refs/notes/code-review
git fetch origin refs/notes/code-review