小编典典

如何将 Git 存储库恢复到以前的提交?

git

如何从当前状态恢复到某个提交时的快照?

如果我这样做git log,那么我会得到以下输出:

$ git log
commit a867b4af366350be2e7c21b8de9cc6504678a61b`
Author: Me <me@me.com>
Date:   Thu Nov 4 18:59:41 2010 -0400

blah blah blah...

commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4
Author: Me <me@me.com>
Date:   Thu Nov 4 05:13:39 2010 -0400

more blah blah blah...

commit 0766c053c0ea2035e90f504928f8df3c9363b8bd
Author: Me <me@me.com>
Date:   Thu Nov 4 00:55:06 2010 -0400

And yet more blah blah...

commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50
Author: Me <me@me.com>
Date:   Wed Nov 3 23:56:08 2010 -0400

Yep, more blah blah.

我如何从 11 月 3 日恢复到提交,即 commit 0d1d7fc


阅读 467

收藏
2021-12-31

共1个答案

小编典典

这在很大程度上取决于您所说的“恢复”是什么意思。

暂时切换到不同的提交

如果你想暂时回到它,闲逛,然后回到你所在的地方,你所要做的就是检查所需的提交:

# This will detach your HEAD, that is, leave you with no branch checked out:
git checkout 0d1d7fc32

或者,如果您想在那里进行提交,请继续创建一个新分支:

git checkout -b old-state 0d1d7fc32

要回到原来的位置,只需再次查看您所在的分支。(如果您进行了更改,一如既往地在切换分支时,您必须适当地处理它们。您可以重置以将它们扔掉;您可以将它们藏匿、结帐、藏匿流行以随身携带;您可以提交如果您想在那里开设分支机构,请将它们转移到那里的分支机构。)

硬删除未发布的提交

另一方面,如果您想真正摆脱从那时起所做的一切,则有两种可能性。一,如果您尚未发布任何这些提交,只需重置:

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts, if you've modified things which were
# changed since the commit you reset to.

如果你搞砸了,你已经扔掉了你的本地更改,但你至少可以通过再次重置回到之前的位置。

使用新提交撤消已发布的提交

另一方面,如果您已经发布了作品,您可能不想重置分支,因为这实际上是在重写历史。在这种情况下,您确实可以还原提交。对于 Git,revert 具有非常特殊的含义:使用反向补丁创建提交以将其取消。这样你就不会重写任何历史。

# This will create three separate revert commits:
git revert a867b4af 25eee4ca 0766c053

# It also takes ranges. This will revert the last two commits:
git revert HEAD~2..HEAD

#Similarly, you can revert a range of commits using commit hashes (non inclusive of first hash):
git revert 0d1d7fc..a867b4a

# Reverting a merge commit
git revert -m 1 <merge_commit_sha>

# To get just one, you could use `rebase -i` to squash them afterwards
# Or, you could do it manually (be sure to do this at top level of the repo)
# get your index and work tree into the desired state, without changing HEAD:
git checkout 0d1d7fc32 .

# Then commit. Be sure and write a good message describing what you just did
git commit
2021-12-31