如何使用git rebase -i进行代码压缩

5

我对rebase不太熟悉,之前也没有压缩过提交记录。

当我切换到名为“whatever”的本地分支后,进行git add和git commit操作,然后再进行rebase。

我想这是rebase的正确方式之一:

git rebase -i development

开发是我们的主线分支,我们在其上进行变基提交。当我执行该命令时,我会得到以下结果:enter image description here

我必须向下滚动才能看到我刚刚尝试重新基于开发分支的最新提交:enter image description here

此时我不确定该怎么做。我显然已经提交了我的更改,然后进行了变基。是否有一个压缩命令和需要压缩的内容?我不想压缩开发分支的整个历史记录。压缩是在重新基础之前完成的吗?我有点迷茫。

1个回答

6
你只需要将“pick”这个单词变成“squash”,就可以将标记为“squash”的提交压缩到前一个提交中。
示例:

Git文档:重写历史

$ git log --oneline
acb05b3 Some final commit.
4968dbd Fixing an error in commit df89a81.
df89a81 Something committed too early.
c365eab Another commit...
625889f A commit...
70f29fd The beginning.

我想要将代码库rebase到最近提交之前的三个提交:

$ git rebase -i HEAD~3

这会在文本编辑器中生成以下文本:
pick df89a81 Something committed too early.
pick 4968dbd Fixing an error in commit df89a81.
pick acb05b3 Some final commit.

# Rebase c365eab..acb05b3 onto c365eab (3 command(s))

我将其更改为:

pick df89a81 Something committed too early.
squash 4968dbd Fixing an error in commit df89a81.
pick acb05b3 Some final commit.

# Rebase c365eab..acb05b3 onto c365eab (3 command(s))

离开时,我得到另一个编辑器包含以下内容:
# This is a combination of 2 commits.
# The first commit's message is:

Something committed too early.

# This is the 2nd commit message:

Fixing an error in commit df89a81.

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

我将其更改为:

# This is a combination of 2 commits.
# The first commit's message is:

This is the squashed commit. It and everything after it get new commit hashes.

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

现在如果我查看我的新历史记录:
$ git log --oneline
8792fef Some final commit.
df775c4 This is the squashed commit. It and everything after it get new commit hashes.
c365eab Another commit...
625889f A commit...
70f29fd The beginning.

奇怪的是我看不到列表中的所有选项,有没有办法向上滚动? - PositiveGuy
哪些提交丢失了,你当前在哪个分支上,当前分支与development分支有什么不同?git rebase -i development应该尝试将当前分支中尚未包含在development分支中的每个提交进行变基。 - David Scarlett
啊,好的,如果我向下滚动,我就可以看到我的最新提交了。不确定为什么它不会一开始就把我带到底部。我会添加另一个截图。 - PositiveGuy
啊,可能只是顺序引起了混淆。交互式变基将提交按与 git log 相反的顺序列出。即最旧的在前,最新的在后。 - David Scarlett
如果您指定任何要合并的提交,它将在您关闭第一个文本编辑器后打开第二个文本编辑器,并且该文本编辑器将包含所有要合并的提交的提交消息,并要求您将它们编辑为单个消息。 - David Scarlett
显示剩余5条评论

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