我的提交消息工作流程

2025-05-26

我的提交消息工作流程

本文最初发表于http://shreyasminocha.me/blog

提交消息示例

我对提交信息非常着迷。我经常会花上好几分钟盯着天空,试图找到一个最佳的方式来概括一次提交带来的更改。我严格遵循良好提交信息的七条规则。你可能已经猜到了,我花了一些时间开发一个编写提交信息的工作流程。

我使用 Sublime Text 3 满足大部分文本编辑需求,并且将其设置为我的核心编辑器。

git config --global core.editor "subl -n -w"
Enter fullscreen mode Exit fullscreen mode

注意subl:如果上述命令无法直接使用,则需要您自行安装。安装说明: macOS · Linux · Windows

之前,我曾经使用一个包来为提交信息提供语法高亮。不过,build 3170 已经原生支持了各种 Git 格式,包括提交信息。

Sublime 允许你覆盖特定语法的设置。你可以从 ‹首选项› → ‹设置 - 语法相关› 编辑这些设置。这是我的Git Commit.sublime-settings文件:

{
    "rulers": [50, 72],
    "spell_check": true,
    "word_wrap": "true",
    "wrap_width": 72,
    "font_size": 14,
    "draw_centered": true
}
Enter fullscreen mode Exit fullscreen mode

注意:VS Code 粉丝可以通过这种方式进行操作

我在互联网上的某个地方找到了提交消息的模板:

# If applied, this commit will…


# Explain why this change is being made

# Provide links to any relevant tickets, articles or other resources
Enter fullscreen mode Exit fullscreen mode

这个模板可以让你更轻松地根据我之前提到的七条规则来构建提交。我记不清在哪里找到过这个模板,但在尝试追踪的过程中,我发现了一篇博客文章,它提供了一个非常类似的模板。事实证明,Git 允许你使用文本文件作为提交消息的模板。

git config --global commit.template "/Users/example/dotfiles/commit-msg-template"
Enter fullscreen mode Exit fullscreen mode

刚开始用这个模板的时候,我对我的设置有点小小不满。运行这个模板时,git commitSublime 会弹出,光标还停留在第一行,为了真正地写下信息,我必须把光标移动到下一行。经过一番研究和实验,我解决了这个问题:

git config --global core.editor = "sublime -n -w $1:2"
Enter fullscreen mode Exit fullscreen mode

值末尾$1:2的打开参数,光标位于第 2 行。

我对提交消息文本的另一个不满是注释掉的上面的这个小片段git status

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
Enter fullscreen mode Exit fullscreen mode

虽然这个小提示对新手很有帮助,但最终却很烦人。我在 StackOverflow 上找到了一个有用的答案,建议使用全局钩子 ( globalprepare-commit-msg hook )。如果你还没有全局的 git hooks 目录,请创建一个并告知 git:

git config --global core.hookspath "/Users/example/dotfiles/git-hooks"
Enter fullscreen mode Exit fullscreen mode

在该目录中创建prepare-commit-msg以下内容:

#!/usr/bin/env bash

sed -i.bak '/^# Please/,/^#$/ d' $1 && rm $1.bak
Enter fullscreen mode Exit fullscreen mode

编辑:此代码片段最初使用perl后跟grep。感谢@shaiay@jwmevans_77在评论中提出的建议。

确保钩子已设置为可执行chmod +x。现在,烦人的帮助通知将不再困扰您。

相关 xkcd

最近,我发现了一个非常酷的实用程序,它允许你从命令行验证提交消息。我在一个全局commit-msg钩子中使用了这个实用程序的修改版本,以便自动验证我所做的每个提交。在你的全局 git hooks 目录中创建commit-msg

#!/usr/bin/env bash

commit-msg file $1
Enter fullscreen mode Exit fullscreen mode

注意:以上命令需要commit-msg在您的计算机上。请使用源代码手动$PATH安装npm i -g commit-msg

再次确保脚本已设置为可执行。此钩子的结果是,如果我的提交消息不符合条件,则提交将中止。

无效提交消息的示例

感谢阅读!

进一步阅读

文章来源:https://dev.to/shreyasminocha/how-i-do-my-git-commits-34d
PREV
3 个很酷的开源 UI 前端组件库
NEXT
如何使用 Docker 安装和运行 PostgreSQL?