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

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


当前回答

由于我在这里提出的解决方案中遇到了一些麻烦,我想分享一个非常简单的解决方案(将一个特性分支上的所有提交压缩成一个):

git merge origin/master && git reset --soft origin/master

前面的合并cmd确保,在提交时,没有来自master的最近更改会出现在您的头上!之后,只需提交更改并执行git push -f

其他回答

对我来说是这样的: 我总共提交了4次,并使用了交互式rebase:

git rebase -i HEAD~3

第一次提交仍然存在,我最近进行了3次提交。

如果你卡在接下来出现的编辑器中,你会看到smth:

pick fda59df commit 1
pick x536897 commit 2
pick c01a668 commit 3

你必须先做出承诺,然后把其他人推到上面。你需要的是:

pick fda59df commit 1
squash x536897 commit 2
squash c01a668 commit 3

为此,使用INSERT键更改“插入”和“编辑”模式。

使用:wq保存并退出编辑器。如果您的光标位于这些提交行之间或其他位置,请按ESC并重试。

结果我有两次提交:第一次仍然存在,第二次带有“这是3次提交的组合”的消息。

详情请点击此处: https://makandracards.com/makandra/527-squash-several-git-commits-into-a-single-commit

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

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

从日志开始

git log --oneline

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

git reset --soft <#sha#>

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

git status

确保所有内容都是绿色的,否则运行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

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

zsh: no matches found: HEAD^{tree}

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

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

unsetopt nomatch

这对我来说效果最好。

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.