为什么 git 接受以哈希符号开头的提交消息

Why git accepts commit messages starting with hash symbol

使用 Git 2.11.1.windows.1,SourceTree 1.10.20.1.

我虽然默认情况下 git 忽略提交消息中以 # 开头的行。但是,使用 SourceTree,我尝试了多行提交消息:

Testing multilines commit message
# Line 2
# Line 3

令人惊讶的是,所有 3 行都被记录为提交消息(由 git log 看到)。可能git需要配置一个默认的注释字符,所以我设置

git config --global core.commentChar "#"

然后撤消 git reset --soft HEAD^ 的提交并使用相同的 3 行消息重新提交(使用 SourceTree,不知道如何在命令行中制作多行提交消息)。以#开头的行仍然被接受。

git 提交消息中的注释行如何工作?

# 作为评论不是 Git 提交消息的规则。相反,它是通过编辑器编写提交消息的规则。

据我所知,这是为了允许 Git 向提交作者显示说明和其他信息。

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#       new file:   what
#

这被保存为.git/COMMIT_EDITMSG。当您的编辑器关闭时,Git 读取该文件,删除注释(和其他特殊内容),并使用剩下的内容作为提交消息。

来自 git-提交文档...

$GIT_DIR/COMMIT_EDITMSG

This file contains the commit message of a commit in progress. If git commit exits due to an error before creating a commit, any commit message that has been provided by the user (e.g., in an editor session) will be available in this file, but will be overwritten by the next invocation of git commit.

顺便说一下,您可以通过不提供未注释的行来中止提交。

例如,如果您使用 git commit -m,则不需要任何这些,以 # 开头的消息就可以了。

$ git ci -m '# message with a comment'
[master 7c6a630] # message with a comment
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 that
$ git log
commit 7c6a630a9c84fda585601edef0b18e7a8683dffa (HEAD -> master)
Author: Michael G. Schwern <schwern@pobox.com>
Date:   Wed Feb 22 20:51:36 2017 -0800

    # message with a comment
$ cat .git/COMMIT_EDITMSG
# message with a comment

git commit has an option to control this behavior, --cleanup。有多种模式可以去除注释、清理空白或什么都不做。默认值为“如果要编辑消息,则与条带相同。否则为空白。”这可以通过 commit.cleanup 配置变量进行控制。


如果您真的想要,您可以使用a commit-msg hook确保评论总是被删除。