【问题标题】:My commit-msg hook - when using full editor, comments are added to commit message我的 commit-msg 钩子 - 使用完整编辑器时,将注释添加到提交消息中
【发布时间】:2014-05-21 07:49:11
【问题描述】:

我想用我的分支名称自动在我的提交消息前面加上方括号,例如:

[分行名称]进行了更改

这是我的 commit-msg 钩子:

#!/bin/sh
#
# Automatically adds branch name and branch description to every commit message.
#
BRANCH=$(git symbolic-ref HEAD | awk -F'/' '{print $3}')

if [ -n "$BRANCH" ]; then
        echo ["$BRANCH"'] '$(cat "$1") > "$1"
fi

如果我使用 git commit -am "Commit message",这个钩子可以正常工作。但是如果我简单地使用 git commit 来使用完整的编辑器,我的提交消息会获得附加的 cmets,例如:

[TestHook] Test # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On

我从网络上的一个示例中复制了 commit-msg 脚本,并根据我的需要进行了一些修改。但是,我不是 bash 脚本专家,所以我怀疑我的脚本有问题。希望得到一些帮助!

谢谢!

【问题讨论】:

    标签: git


    【解决方案1】:

    您可以尝试更改提交消息模板(参见git commit):

    编辑提交消息时,使用给定文件中的内容启动编辑器。
    commit.template 配置变量通常用于将此选项隐式地赋予命令。

    试一试:

    git config commit.template /path/to/empty/commit/message/template
    

    如果该模板文件为空,您的 git commit 不应附加任何内容。

    【讨论】:

    • 这是一个很好的解决方法,但我希望首先弄清楚为什么 commit-msg 脚本会导致问题。不过我会记住这一点,谢谢!
    • @odinsride 它应该会导致问题,因为它使用了默认的提交消息模板。因此我的解决方法。
    • 所以我已经尝试过了,但是当我发出 git commit 时,消息模板仍然包含那些 #cmets。我将模板设置为 ~/.gitmessage.txt,文件中有一行写着“Something”,只是为了测试功能。当我发出 git commit 时,我看到:Something^M # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On branch TestHook # Changes to be committed: # modified: test_file_renamed.txt #
    【解决方案2】:

    经过大量谷歌搜索,我更正了我的脚本以使用 grep 而不是 cat,现在它运行良好:

    #!/bin/sh
    #
    # Automatically adds branch name to every commit message.
    #
    BRANCH=$(git symbolic-ref HEAD | awk -F'/' '{print $3}')
    
    if [ -n "$BRANCH" ]; then
            echo ["$BRANCH"'] '$(egrep -v '(^#|^\s*$|^\s*\t*#)' "$1") > "$1"
    fi
    

    grep 命令排除以 # 开头的行,或以空格/制表符开头后跟 # 的行(并非完全必要,但无论如何都扔掉了)。

    【讨论】:

    • 很棒的收获。那么,提交消息模板毕竟不涉及。 +1
    猜你喜欢
    • 2013-10-16
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2020-12-11
    • 2019-07-19
    • 2013-02-17
    相关资源
    最近更新 更多