如何将整个存储库压缩到第一次提交?

我可以将base转换为第一次提交,但这将留给我2次提交。 有没有办法在第一个提交之前引用这个提交?


当前回答

我读过一些关于移植的东西,但从来没有深入研究过。

不管怎样,你可以手动压缩最后2次提交,就像这样:

git reset HEAD~1
git add -A
git commit --amend

其他回答

从git 1.6.2开始,你可以使用git rebase——root -i

对于除第一次提交外的每个提交,将pick更改为squash。

以下是我最后是如何做到这一点的,以防其他人也能做到:

记住,做这样的事情总是有风险的,在开始之前创建一个保存分支从来都不是一个坏主意。

从日志开始

git log --oneline

滚动到第一次提交,复制SHA

git reset --soft <#sha#>

将<#sha#>替换为从日志中复制的sha

git status

确保所有内容都是绿色的,否则运行git add -A

git commit --amend

将当前所有更改修改为当前首次提交

现在强制推这个分支,它会覆盖那里的内容。

假设你的分支中有3个提交,并且它已经被推送到远程分支。

例子:

git log -4

将显示如下结果:

<your_third_commit_sha>
<your_second_commit_sha>
<your_first_commit_sha>
<master_branch_commit_sha - your branch created from master>

你想把最后3次提交压缩成一次提交,然后推送到远程分支。以下是步骤。

git reset --soft <master_branch_commit_sha>

现在所有提交的更改都被集成但未提交。验证:

git status

用一条消息提交所有更改:

git commit -m 'specify details'

强制将单次提交推到远程分支:

git push -f

这对我来说效果最好。

git rebase -X ours -i master

这将使git更喜欢你的特性分支;避免艰苦的合并编辑。您的分支需要与主机同步。

ours
           This resolves any number of heads, but the resulting tree of the merge is always that of the current
           branch head, effectively ignoring all changes from all other branches. It is meant to be used to
           supersede old development history of side branches. Note that this is different from the -Xours
           option to the recursive merge strategy.

假设你有这些从06年到10年的提交。

您希望将06年后的提交合并为一个提交Id。

commit 10
commit 09  
commit 08  
commit 07  
commit 06

你可以软复位git。

git reset --soft "06"

然后,运行下面的命令将这些更改推送到远程分支。

git push origin HEAD --force

现在,您之前所做的所有提交都应该作为您的本地更改可用,您可以将所有这些提交合并到单个提交中。

现在,新的提交结构应该如下所示:

commit <new_commit_containing_all_7_8_9_10>
commit 06