我可以恢复在交互式变基期间丢失的提交吗?

Can I recover commits lost during interactive rebase?

所以我有这种奇怪的情况。

我正在对 4 次提交进行交互式变基。我试图压扁,但我做错了,我收到以下错误:

error: cannot 'squash' without a previous commit You can fix this with
'git rebase --edit-todo' and then run 'git rebase --continue'. Or you
can abort the rebase with 'git rebase --abort'.

我决定 运行 git rebase --edit-todo 当我这样做时,只出现最后一次提交。我将它从 squash 更改为 pick 和 运行 git rebase --continue 但现在看来我试图压缩的其他 3 个提交已不存在了。
所以我早上的工作似乎丢失了。
一定有办法恢复那些,对吧?
我该怎么做?

你应该:

git reflog

# Write down the lost commit hash

git cherry-pick <LOST_COMMIT_HASH>

这是Git。什么都不会丢失。整个变基是不可撤销的!

只需使用git reflog定位你在变基前的位置。很明显它是哪一个,因为第一个将描述变基。

现在只需重新设置为该提交即可。 Presto,你已经撤消了 rebase。

现在只要下次正确执行变基即可。


例子。我先从这个情况说起:

* 18c9859 (HEAD -> what) zz
* e1af86b yy
* 47853b7 xx
* 45ebca0 (origin/main, origin/HEAD, main) zzz

我交互式变基,清除 yyxx

% git rebase -i main
Successfully rebased and updated refs/heads/what.

现在的情况是:

* e2d37cd (HEAD -> what) zz
* 45ebca0 (origin/main, origin/HEAD, main) zzz

但这不是我想做的! xxyy 不见了!哦不!

但是等等。没问题。我们可以撤消。首先,查看 reflog:

% git reflog
e2d37cd (HEAD -> what) HEAD@{0}: rebase (finish): returning to refs/heads/what
e2d37cd (HEAD -> what) HEAD@{1}: rebase (pick): zz
45ebca0 (origin/main, origin/HEAD, main) HEAD@{2}: rebase (start): checkout main
18c9859 HEAD@{3}: commit: zz [this is it]
...

好的,撤消:

% git reset --hard HEAD@{3}

全部修复!我回到了完全我在变基之前的位置:

* 18c9859 (HEAD -> what) zz
* e1af86b yy
* 47853b7 xx
* 45ebca0 (origin/main, origin/HEAD, main) zzz

派对开始!