回答

收藏

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

技术问答 技术问答 308 人阅读 | 0 人回复 | 2023-09-11

提交时如何从当前状态恢复快照?# D5 C/ t1 y: G) K
假如我这样做git log,然后我将获得以下输出:0 D1 \2 N; g/ K
more blah blah.more blah blah.如何从 11 月 3 日恢复到提交,即 commit 0d1d7fc?
* L  {6 S* ^! _. N! Y                                                                7 g9 |, c6 O, e
    解决方案:                                                                8 s- _7 i4 _9 y2 r( O5 i/ {0 Z
                                                                这在很大程度上取决于你所说的恢复是什么意思。- y/ l: Q- e2 F
暂时切换到不同的提交如果你想暂时回到它,闲逛,然后回到你所在的地方,你所要做的就是检查所需的提交:
; M( o% N% c5 `+ H
    # This will detach your HEAD,that is,leave you with no branch checked out:git checkout 0d1d7fc324 |" `( M8 J" s' j$ y- S3 w
或者,如果您想在那里提交,请继续创建一个新的分支:
4 f2 U$ ^' ?6 u" k/ G# Ogit checkout -b old-state 0d1d7fc32回到原来的位置,只要再次检查你的分支机构。(如果你改变了它,你必须像往常一样处理它们。你可以把它们重置扔掉;你可以把它们藏起来,结账,藏起来很受欢迎;如果你想在那里开设分支机构,请把它们转移到那里。
2 M& B& [4 J. o+ ~5 [  |( A. S! s硬删除未发布的提交另一方面,如果你真的想摆脱从那时起所做的一切,有两种可能性。1、如果您没有发布任何这些提交,只需重置:. w5 M% c  p& g
    # 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 stashgit reset --hard 0d1d7fc32git 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.& M4 D9 H( g/ l& G8 k# H6 q
如果你搞砸了,你已经扔掉了当地的变化,但至少你可以通过重置回到以前的位置。
; G; W& k6 F) _使用新提交撤销已发布的提交另一方面,如果你已经发表了作品,你可能不想重置分支,因为它实际上是在重写历史。在这种情况下,您确实可以恢复提交。Git,revert 有一个非常特殊的含义:使用反向补丁创建并提交以取消它。这样你就不会重写任何历史了。( Q5 E4 b" u! j1 Q
    # 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 commitgit revert -m 1 # 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 didgit commit8 V6 g, p0 o6 W. X" Z$ U# H: E
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则