git:在提交模板中显示最后一次提交的消息

13

git commit 打开文本编辑器,并显示有关要提交的更改的某些信息:

# 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:
#   (use "git reset HEAD <file>..." to unstage)
#

#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#

我想扩展这个模板来显示:

  • 最近N次提交的第一行消息和/或
  • 最后一次提交的完整消息

当前分支的。我该怎么做?

1个回答

14

这将使用 git hooks

  • 在您的项目根目录中导航到 .git/hooks/
  • 现在创建文件 prepare-commit-msg
  • 添加以下代码:
#!/bin/sh
ORIG_MSG_FILE="$1"  # Grab the current template
TEMP=`mktemp /tmp/git-msg-XXXXX` # Create a temp file
trap "rm -f $TEMP" exit # Remove temp file on exit

MSG=`git log -1 --pretty=%s` # Grab the first line of the last commit message

(printf "\n\n# Last Commit: %s \n\n" "$MSG"; cat "$ORIG_MSG_FILE") > "$TEMP"  # print all to temp file
cat "$TEMP" > "$ORIG_MSG_FILE" # Move temp file to commit message
  • chmod +x prepare-commit_message

借鉴自增强git提交信息模板

您可以使用%b%B来获取整个提交消息,但是可能会遇到多行提交的问题。可以尝试使用%-b%-B,或者在文档(滚动到格式)中了解更多信息。


记得删除临时文件,并在 printf 结尾添加 \n(它不像 echo 一样包含换行符)。 - Brian Campbell
1
应该这样做(通常放在创建临时文件的行之后,以便如果后续行退出,它仍将运行):trap "rm -f $TEMP" exit - Brian Campbell
1
哦,是的,对于printf,通常应使用格式字符串并将$MSG作为单独变量提供,以便它不会被解释为格式字符串。printf "\n\n# 最后提交:%s \n\n" "$MSG"。您不想让提交消息“用\r\n替换\n以实现Windows兼容性”导致这些实际换行符出现在您的模板中。 - Brian Campbell
1
没问题,很高兴能帮助您。最后一件事是,正如您所说,这仅适用于单行提交消息,但您正在使用%B来获取整个提交消息。 您可以使用%s仅获取标题或提交消息的第一行,因此它不会在多行提交消息上出错。 - Brian Campbell
1
请注意,我必须将文件保存为“prepare-commit-msg”才能使其正常工作。 - Sebastian
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接