问题描述
我进行了 git commit 和后续推送.我想更改提交消息.如果我理解正确,这是不可取的,因为在我进行此类更改之前,有人可能已经从远程存储库中提取了数据.如果我知道没人拉过怎么办?
I have made a git commit and subsequent push. I would like to change the commit message. If I understand correctly, this is not advisable because someone might have pulled from the remote repository before I make such changes. What if I know that no one has pulled?
有没有办法做到这一点?
Is there a way to do this?
推荐答案
更改历史
如果是最近的提交,你可以简单地这样做:
Changing history
If it is the most recent commit, you can simply do this:
git commit --amend
这会打开带有最后提交消息的编辑器,并让您编辑该消息.(如果您想清除旧消息并使用新消息,可以使用 -m
.)
This brings up the editor with the last commit message and lets you edit the message. (You can use -m
if you want to wipe out the old message and use a new one.)
然后当你推送时,这样做:
And then when you push, do this:
git push --force-with-lease <repository> <branch>
或者您可以使用+":
git push <repository> +<branch>
或者你可以使用--force
:
git push --force <repository> <branch>
使用这些命令时要小心.
Be careful when using these commands.
如果其他人将更改推送到同一分支,您可能希望避免破坏这些更改.
--force-with-lease
选项是最安全的,因为如果有任何上游更改,它将中止 (
If someone else pushed changes to the same branch, you probably want to avoid destroying those changes. The
--force-with-lease
option is the safest, because it will abort if there are any upstream changes (
如果没有明确指定分支,Git 将使用默认推送设置.如果您的默认推送设置是匹配",那么您可能会同时销毁多个分支上的更改.
If you don't specify the branch explicitly, Git will use the default push settings. If your default push setting is "matching", then you may destroy changes on several branches at the same time.
任何已经拉取的人现在都会收到一条错误消息,他们需要通过执行以下操作来更新(假设他们自己没有进行任何更改):
Anyone who already pulled will now get an error message, and they will need to update (assuming they aren't making any changes themselves) by doing something like this:
git fetch origin
git reset --hard origin/master # Loses local commits
使用 reset --hard
时要小心.如果您对分支进行了更改,这些更改将被销毁.
Be careful when using reset --hard
. If you have changes to the branch, those changes will be destroyed.
销毁的数据实际上只是旧的提交消息,但是 --force
不知道这一点,并且也会很乐意删除其他数据.因此,将 --force
视为我想销毁数据,并且我确定要销毁哪些数据."但是当被破坏的数据被提交时,你通常可以从引用日志中恢复旧的提交——数据实际上是孤立的而不是被破坏的(尽管孤立的提交会被定期删除).
The destroyed data is really just the old commit message, but --force
doesn't know that, and will happily delete other data too. So think of --force
as "I want to destroy data, and I know for sure what data is being destroyed." But when the destroyed data is committed, you can often recover old commits from the reflog—the data is actually orphaned instead of destroyed (although orphaned commits are periodically deleted).
如果您不认为自己在破坏数据,那么请远离 --force
... 可能会发生坏事.
If you don't think you're destroying data, then stay away from --force
... bad things might happen.
这就是 --force-with-lease
更安全的原因.
This is why --force-with-lease
is somewhat safer.
这篇关于推送后更改 git commit 消息(假设没有人从远程拉取)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!