在 GitHub 上压缩多个提交记录

8
我希望将两个最近提交的commit合并为一个,同时保留"first"和"second"的提交信息。我先拉取主分支,然后使用以下命令:
git rebase -i HEAD~2 master

它会在编辑器中显示两个提交,就像这样:
pick first
pick second

然后我将这个编辑器改为:
pick first
squash second

保存更改后,我收到了以下消息:
Successfully rebased and updated refs/heads/master.

它并没有改变远程主分支的任何内容。为了应用这些更改,我使用了git push命令,并得到了以下错误:

To https://github.com/aneelatest/GITtest.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/test/GITtest.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

然后我再次运行 git pull 命令,它会合并 origin master 分支,并创建另一个提交记录,提交信息如下:

Merge branch 'master' of https://github.com/aneelatest/GITtest

在此之后,当我运行git push时,它会将这两个提交压缩成一个提交,并使用消息“first”。 问题在于,在远程主分支中,现在有四个提交:
first
second
Merge branch 'master' of https://github.com/test/GITtest
first

我只想要一个提交,这个提交应该是合并后的提交,并且提交信息是“first”。请问我错在哪了?

您无需再压缩:所有者可以替您完成(自2016年3月起):请参阅https://dev59.com/omgu5IYBdhLWcg3wWVuF#36377439 - VonC
1个回答

10

git rebase 可以修改提交历史记录,因此可能会造成问题。如果这些被修改的提交还没有被推送到远程仓库,那么就不会有问题,但是如果这些提交已经被推送到了远程仓库,那么再次推送时就会遇到拒绝操作。

当你从 GitHub 上拉取代码时,它会合并两个历史版本,并应用你的 "Squash commit",这就是混乱的原因。

结论:如果您想要修改已经被推送的提交,您有两种选择:

  • 不要这样做
  • 运行 git push --force 命令,这将覆盖远程仓库的历史记录,并提示其他开发者注意到您已经修改过历史记录,所以他们在下一次拉取代码时可能会看到一些奇怪的东西。

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