如何更正 Git 提交消息
谁不知道呢:你因为某种原因不得不完成工作,然后快速执行了git commit
一次,却发现提交信息中有一个拼写错误或缺失了什么。甚至更糟:你在推送到远程后才意识到这一点……
我很喜欢在提交信息中使用醒目的表情符号。这样,我就能在 git 提交日志中对提交进行直观的分类,并轻松识别错误修复、新增内容或依赖项更新。为了兼容终端输出,我使用了短代码(例如:key:
用于与安全性相关的提交),而不是直接插入表情符号 (🔑)。你可能会说我太挑剔了,但我认为如果表情符号短代码出现拼写错误,提交或文件列表会非常难看:
幸运的是,有一些方法可以在提交后修改提交信息。让我们来看看:
更正最近未推送的提交消息
这是最简单的方法。只需输入以下内容:
git commit --amend -m "correct commit message"
如果您现在将更改推送到远程,则会出现更正的提交消息。
使用 VS Code 时,您可以从···菜单撤消上次提交:
CTRL
或者简单地使用+ SHIFT
+打开命令提示符P
并输入“undo”。
更正最近推送的提交消息
如果您已经推送了最后一次提交,您可以用同样的方式纠正它 - 但您必须强制推送错误的提交:
git commit --amend -m "correct commit message"
git push --force
更正较旧的提交消息
这个有点棘手。你需要找出需要回溯多少个提交才能找到你想要修正的提交。有了这些信息,你就可以使用
git rebase -i HEAD~n
在默认文本编辑器中显示最近的n
提交。以下是最近 3 次提交的输出:
$ git rebase -i HEAD~3
pick da47737 :x: remove outdated entry
pick a27d81a :shirtt: clean linter warnings
pick f1db3c9 :hammer: fix missing condition
# Rebase 0ceed9a..f1db3c9 onto 0ceed9a (3 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
现在,将您想要更正的每个提交消息前的单词替换pick
为,即:reword
$ git rebase -i HEAD~3
pick da47737 :x: remove outdated entry
reword a27d81a :shirtt: clean linter warnings
pick f1db3c9 :hammer: fix missing condition
保存提交列表,并在后续每个提交文件中更正提交信息。和之前一样,你需要强制推送更改。
现在,在纠正了错误的表情符号短代码后,我在查看提交日志时又能找到平静了。😎
重要附注
- 提交消息属于提交本身。因此,修改它意味着创建一个新的提交,并用错误的提交消息替换它。
- 不建议强制推送,因为这会更改仓库历史记录。这意味着您必须手动修复仓库现有克隆的本地历史记录,这将使协作者的贡献更加困难。
编辑于:2019 年 10 月 19 日(添加 VS Code 示例,添加到边注 2)
最初发布于:2019 年 10 月 10 日,Medium