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

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


当前回答

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

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

从日志开始

git log --oneline

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

git reset --soft <#sha#>

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

git status

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

git commit --amend

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

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

其他回答

如果您想要做的只是将所有提交压缩到根提交,那么while

git rebase --interactive --root

可以工作,但对于大量提交(例如,数百个提交)来说是不切实际的,因为在生成交互式的重基编辑器提交列表以及运行重基本身时,重基操作可能会运行得非常慢。

当你压缩大量的提交时,这里有两个更快更有效的解决方案:

替代解决方案#1:孤儿分支

你可以简单地在你当前分支的顶端(即最近的提交)创建一个新的孤儿分支。这个孤儿分支形成了一个全新的独立提交历史树的初始根提交,这实际上相当于压缩了你所有的提交:

git checkout --orphan new-master master
git commit -m "Enter commit message for your new initial commit"

# Overwrite the old master branch reference with the new one
git branch -M new-master master

文档:

git-checkout(1)手册。

备选方案2:软复位

另一个有效的解决方案是简单地使用混合或软重置到根提交<root>:

git branch beforeReset

git reset --soft <root>
git commit --amend

# Verify that the new amended root is no different
# from the previous branch state
git diff beforeReset

文档:

git-reset(1)手动页面。

一行6个字:

git checkout --orphan new_root_branch  &&  git commit

也许最简单的方法是用工作副本的当前状态创建一个新的存储库。如果你想保留所有的提交消息,你可以先执行git log > original.log,然后在新的存储库中编辑你的初始提交消息:

rm -rf .git
git init
git add .
git commit

or

git log > original.log
# edit original.log as desired
rm -rf .git
git init
git add .
git commit -F original.log

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

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

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

最简单的方法是使用'plumbing'命令update-ref删除当前分支。

你不能使用git branch -D,因为它有一个安全阀来阻止你删除当前的分支。

这会让你回到“初始提交”状态,在那里你可以开始一个新的初始提交。

git update-ref -d refs/heads/master
git commit -m "New initial commit"