结合Git存储库的前两个提交?

Chr*_*ian 194 git rebase git-rebase git-rewrite-history

假设您有一个包含三个提交A,BC的历史记录:

A-B-C
Run Code Online (Sandbox Code Playgroud)

我想将两个提交AB组合到一个提交AB:

AB-C
Run Code Online (Sandbox Code Playgroud)

我试过了

git rebase -i A
Run Code Online (Sandbox Code Playgroud)

这打开了我的编辑器,其中包含以下内容:

pick e97a17b B
pick asd314f C
Run Code Online (Sandbox Code Playgroud)

我改成这个

squash e97a17b B
pick asd314f C
Run Code Online (Sandbox Code Playgroud)

然后Git 1.6.0.4说:

Cannot 'squash' without a previous commit
Run Code Online (Sandbox Code Playgroud)

有办法还是不可能?

kos*_*tmo 161

使用git rebase -i --root 作为的Git 版本1.7.12.

在互动变基文件,改变提交的第二线压扁并保留其他线路的挑选:

pick f4202da A
squash bea708e B
pick a8c6abc C
Run Code Online (Sandbox Code Playgroud)

这将把两个提交AB组合成一个提交AB.

发现在这个答案.


Dav*_*lau 126

你试过:

git rebase -i A
Run Code Online (Sandbox Code Playgroud)

如果你继续edit而不是squash:有可能这样开始:

edit e97a17b B
pick asd314f C
Run Code Online (Sandbox Code Playgroud)

然后运行

git reset --soft HEAD^
git commit --amend
git rebase --continue
Run Code Online (Sandbox Code Playgroud)

完成.

  • 如果你这样做是为了安静地修复github要点,你必须在提交中添加-m"initial".;-) (4认同)

CB *_*ley 64

A是最初的提交,但现在你想B成为最初的提交.git提交是整个树,而不是差异,即使它们通常是根据它们引入的差异来描述和查看的.

即使A和B以及B和C之间有多个提交,此配方仍然有效.

# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout <sha1_for_B>

# reset the branch pointer to the initial commit,
# but leaving the index and working tree intact.
git reset --soft <sha1_for_A>

# amend the initial tree using the tree from 'B'
git commit --amend

# temporarily tag this new initial commit
# (or you could remember the new commit sha1 manually)
git tag tmp

# go back to the original branch (assume master for this example)
git checkout master

# Replay all the commits after B onto the new initial commit
git rebase --onto tmp <sha1_for_B>

# remove the temporary tag
git tag -d tmp
Run Code Online (Sandbox Code Playgroud)


Lok*_*oki 10

在交互式rebase的情况下,您必须在A之前执行此操作,以便列表将是:

pick A
pick B
pick C
Run Code Online (Sandbox Code Playgroud)

成为:

pick A
squash B
pick C
Run Code Online (Sandbox Code Playgroud)

如果A是初始提交,则必须在A. Git考虑差异之前进行不同的初始提交,它将对(A和B)和(B和C)之间的差异起作用.因此壁球不适用于你的例子.


小智 9

在这种情况下,你必须提交的数百或数千使用kostmo的答案

git rebase -i --root
Run Code Online (Sandbox Code Playgroud)

可能是不切实际和缓慢的,只是由于rebase脚本必须处理两次的大量提交,一次生成交互式rebase编辑器列表(您选择每次提交要采取的操作),以及一次实际执行重新提交提交.

这是一种替代解决方案,通过不首先使用交互式rebase来避免生成交互式rebase编辑器列表的时间成本.通过这种方式,它与Charles Bailey的解决方案类似.您只需从第二次提交创建一个孤立分支,然后在其上面重新定义所有后代提交:

git checkout --orphan orphan <second-commit-sha>
git commit -m "Enter a commit message for the new root commit"
git rebase --onto orphan <second-commit-sha> master
Run Code Online (Sandbox Code Playgroud)

文档