我对git中的整个重基特性有点陌生。假设我做了以下提交:

A -> B -> C -> D

后来,我意识到D包含了一个依赖于a中添加的一些新代码的修复,并且这些提交属于一起。我如何把A和D挤在一起,而不去管B和C ?


你可以运行git rebase——interactive,将D重新排列在B之前,然后将D压缩到A中。

Git会打开一个编辑器,你会看到这样一个文件,例如:Git rebase——interactive HEAD~4

pick aaaaaaa Commit A
pick bbbbbbb Commit B
pick ccccccc Commit C
pick ddddddd Commit D

# Rebase aaaaaaa..ddddddd onto 1234567 (4 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
#
# 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 aaaaaaa Commit A
squash ddddddd Commit D
pick bbbbbbb Commit B
pick ccccccc Commit C

git现在会将A和D的更改合并到一个提交中,然后再提交B和C。当您不想保留D的提交消息时,您可以使用fixup关键字而不是squash。关于修复的更多信息,你可以参考git rebase文档,或者看看这个问题,它有一些很好的答案。


$ git checkout master

$ git log --oneline

D
C
B
A

$ git rebase - to HEAD^^^ HEAD^

$ git log --oneline

D
A

注意:您不应该以任何方式更改已经推到另一个回购的提交,除非您知道后果。

Git日志——oneline -4

D commit_message_for_D
C commit_message_for_C
B commit_message_for_B
A commit_message_for_A

Git rebase—交互式

pick D commit_message_for_D
pick C commit_message_for_C
pick B commit_message_for_B
pick A commit_message_for_A

类型i(将VIM置于插入模式)

将列表更改为如下所示(您不必删除或包括提交消息)。不要拼错壁球!:

pick C commit_message_for_C
pick B commit_message_for_B
pick A commit_message_for_A
squash D

按Esc然后ZZ(保存并退出VIM)

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

commit_message_for_D

# This is the 2nd commit message:

commit_message_for_A

i型

将文本更改为您想要的新提交消息的样子。我建议这是对提交a和D的更改的描述:

new_commit_message_for_A_and_D

按Esc,然后按ZZ

Git日志——oneline -4

E new_commit_message_for_A_and_D
C commit_message_for_C
B commit_message_for_B

git显示

(You should see a diff showing a combination of changes from A and D)

您现在已经创建了一个新的提交e。提交a和D不再在历史记录中,但并没有消失。此时你仍然可以通过git rebase -hard D暂时恢复它们(git rebase -hard会破坏任何本地更改!)


对于使用SourceTree的用户:

确保您还没有推送提交。

知识库>交互Rebase… 将D(较新的提交)拖到A(较旧的提交)的正上方 确保提交D突出显示 点击“压缩”


交互式rebase工作得很好,直到你有一个大的特性分支,有20-30次提交和/或从master合并或/和修复在你的分支中提交时的冲突。即使通过历史记录找到我的提交,用壁球代替pick,在这里也不起作用。所以我在寻找另一种方式,找到了这篇文章。 我在单独的分支上做了修改:

git checkout master
git fetch
git pull
git merge branch-name
git reset origin/master
git branch -D branch-name
git checkout -b branch-name
git add --all
#Do some commit
git push -f --set-upstream origin branch-name

在此之前,我得到了大约30个提交的pull请求,其中2-3个合并来自master +修复冲突。在这之后,我一次就搞定了公关。

附注:这里是bash脚本在自动代码中执行此步骤。