Git - 我们可以恢复已删除的提交吗?

Git - Can we recover deleted commits?

我很惊讶,我在 SO 上找不到这个问题的答案。

Can we recover/restore deleted commits in git?

例如,我是这样做的:

# Remove the last commit from my local branch
$ git reset --hard HEAD~1

# Force push the delete
$ git push --force

现在,有没有办法找回被删除的提交? git 是否在内部记录(记录)删除?

是的,您可以在 reflog 中找到您的提交,使用:

git reflog

显示 are/were 在您的存储库中创建的所有提交 - 在此之后您应该通过签出命令签出删除的提交

git checkout <your commit-SHA>

或cherry-pick 由:

git cherry-pick <your commit-SHA>

尝试 git reflog,又名参考日志,它允许您返回到本地存储库中的历史记录。

https://git-scm.com/docs/git-reflog

要返回到该提交,您可以使用 reflog 查找它的引用。

Reference logs, or "reflogs", record when the tips of branches and other references were updated in the local repository.

运行 这个命令:

git reflog

扫描前几个条目,找到丢失的提交。跟踪该提交的标识符(您可以使用第一列或第二列)。我们称标识符为 "ID".

如果您在重置后没有做任何额外的工作 --hard 您可以:

git reset --hard ID
git push -f origin master

如果您在重置后进行了其他工作,您可以 cherry-pick 如果像这样回到您的分支:

git cherry-pick ID
git push origin master