git - merge 或 rebase 任意数量的提交

标签 git git-rebase squash

假设我的本地 git log 显示:

739b36d3a314483a2d4a14268612cd955c6af9fb a
...
c42fff47a257b72ab3fabaa0bcc2be9cd50d5c89 x
c4149ba120b30955a9285ed721b795cd2b82dd65 y
dce99bcc4b79622d2658208d2371ee490dff7d28 z

我的远程 git log 显示:

c4149ba120b30955a9285ed721b795cd2b82dd65 y
dce99bcc4b79622d2658208d2371ee490dff7d28 z

最简单的方法是什么(假设任意数量的本地提交):

527b5810cfd8f45f18ae807af1fe1e54a0312bce a ... x
c4149ba120b30955a9285ed721b795cd2b82dd65 y
dce99bcc4b79622d2658208d2371ee490dff7d28 z

最佳答案

有时,您可能不想使用交互式 Rebase

如果 A 到 X 之间的中间提交数量相对较小,您可以通过使用 interactive rebasing 来解决:

git rebase -i origin/master

但是,根据我的个人经验,对大量提交使用交互式 rebase 很慢。我一次对大约一百个提交运行了一个交互式 rebase(在使用 Git Bash 的 Windows 机器上),msysgit 花了很长时间来生成交互式 rebase 提交编辑器,它允许您选择要运行的操作在哪个提交上,因为,好吧,列表最终变得非常大。

在这种情况下,您有几个解决方法。

备选方案 #1:git reset

混合重置和软重置可用于修改您的工作树或暂存区域(分别)以聚合/收集两次提交 A 和 Y 之间的所有更改,之后您可以一次提交所有修改提交。

我只会举一个软重置的例子,因为它已经为你准备好了一切,而如果你使用混合重置,你无论如何都必须准备修改:

# You don't need to create the temp branch A if you
# copy the commit sha A down somewhere so that you can remember it.
git branch temp A

git reset --soft Y
git commit -m "Squash commits A through X"

# Verify that this new commit is equivalent to the final state at A
git diff A

备选方案 #2:使用补丁

另一种选择是简单地使用补丁。只需生成 A 到 Y 之间差异的差异补丁,然后将补丁作为新提交应用到 Y 之上:

git diff y a > squash.patch
git checkout -b squash-branch y
git apply squash.patch
git commit -m "Squash commits A through X"

# Verify that this new commit is equivalent to the final state at A
git diff A

正如 @A-B-B in the comments 所指出的,如果涉及二进制文件,这将无法正常工作。除了文本文件之外,git diff --binary 还可用于输出二进制文件的差异,但我不确定这些差异是否也可以用作补丁。

关于git - merge 或 rebase 任意数量的提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161793/

相关文章:

git - 为什么一个分支的更改会影响 git 中的另一个分支?

Git - merge 与 rebase

git - git rebase 在哪里修改

git - merge --squash 和 rebase 有什么区别?

git - 将 "local"数据工厂更改提交到 Azure DevOps GIT

android - GitHub项目未引入Android Studio

git - 我如何压缩所有提交历史并推送到另一个远程存储库?

git - 推送后如何在 git 中压缩提交?

git - 位桶访问不起作用

Git rebase : finding the "next" commit to be rebased?