如何将整个存储库压缩到第一次提交?
我可以将base转换为第一次提交,但这将留给我2次提交。 有没有办法在第一个提交之前引用这个提交?
如何将整个存储库压缩到第一次提交?
我可以将base转换为第一次提交,但这将留给我2次提交。 有没有办法在第一个提交之前引用这个提交?
当前回答
一行6个字:
git checkout --orphan new_root_branch && git commit
其他回答
由于我在这里提出的解决方案中遇到了一些麻烦,我想分享一个非常简单的解决方案(将一个特性分支上的所有提交压缩成一个):
git merge origin/master && git reset --soft origin/master
前面的合并cmd确保,在提交时,没有来自master的最近更改会出现在您的头上!之后,只需提交更改并执行git push -f
首先,使用git rebase -interactive将所有提交压缩成一个提交。现在就剩下两个壁球提交了。要做到这一点,请阅读任何一本
如何合并Git存储库的前两次提交? Git:如何压缩前两次提交?
假设你的分支中有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
如果您想要做的只是将所有提交压缩到根提交,那么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)手动页面。
我用HEAD^{tree}尝试了不同的命令,但从zsh得到了这个错误:
zsh: no matches found: HEAD^{tree}
这是ohmyzsh处理扩展的方式,查看这个问题了解更多细节: https://github.com/ohmyzsh/ohmyzsh/issues/449
最简单的解决方法是运行这个命令:
unsetopt nomatch