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

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


当前回答

假设你有这些从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

其他回答

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

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

从日志开始

git log --oneline

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

git reset --soft <#sha#>

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

git status

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

git commit --amend

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

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

我用HEAD^{tree}尝试了不同的命令,但从zsh得到了这个错误:

zsh: no matches found: HEAD^{tree}

这是ohmyzsh处理扩展的方式,查看这个问题了解更多细节: https://github.com/ohmyzsh/ohmyzsh/issues/449

最简单的解决方法是运行这个命令:

unsetopt nomatch

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

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

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

我通常是这样做的:

Make sure everything is committed, and write down the latest commit id in case something goes wrong, or create a separate branch as the backup Run git reset --soft `git rev-list --max-parents=0 --abbrev-commit HEAD` to reset your head to the first commit, but leave your index unchanged. All changes since the first commit will now appear ready to be committed. Run git commit --amend -m "initial commit" to amend your commit to the first commit and change the commit message, or if you want to keep the existing commit message, you can run git commit --amend --no-edit Run git push -f to force push your changes

echo "message" | git commit-tree HEAD^{tree}

这将创建一个带有HEAD树的孤立提交,并在stdout上输出其名称(SHA-1)。然后重置你的分支。

git reset SHA-1

要在一个步骤中完成上述工作:

git reset $(git commit-tree HEAD^{tree} -m "Initial commit.")