回答

收藏

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

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

提交时如何从当前状态恢复快照?
9 k% A" h7 T% D8 _+ Y7 C假如我这样做git log,然后我将获得以下输出:/ b2 M0 f+ {# y* E
more blah blah.more blah blah.如何从 11 月 3 日恢复到提交,即 commit 0d1d7fc?
: n3 i8 M- n9 A) E& S# |                                                                6 N  L7 n+ N; @* O0 S
    解决方案:                                                                6 d5 ~* M% X% q" _/ }
                                                                这在很大程度上取决于你所说的恢复是什么意思。
  D/ U" ?/ H2 [% [( w暂时切换到不同的提交如果你想暂时回到它,闲逛,然后回到你所在的地方,你所要做的就是检查所需的提交:1 g4 o9 p! p* V  o  s
    # This will detach your HEAD,that is,leave you with no branch checked out:git checkout 0d1d7fc32
    6 f( G& ^9 X0 d
或者,如果您想在那里提交,请继续创建一个新的分支:& ^" m" T2 Z& h& c" k' k1 z
git checkout -b old-state 0d1d7fc32回到原来的位置,只要再次检查你的分支机构。(如果你改变了它,你必须像往常一样处理它们。你可以把它们重置扔掉;你可以把它们藏起来,结账,藏起来很受欢迎;如果你想在那里开设分支机构,请把它们转移到那里。
2 i+ R. v! q" y8 v2 U4 ]' E硬删除未发布的提交另一方面,如果你真的想摆脱从那时起所做的一切,有两种可能性。1、如果您没有发布任何这些提交,只需重置:- w2 d5 {1 K) _7 G" o# _
    # 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.& z! z- z- o9 u; L' F
如果你搞砸了,你已经扔掉了当地的变化,但至少你可以通过重置回到以前的位置。/ |1 |& p* Y8 E8 x
使用新提交撤销已发布的提交另一方面,如果你已经发表了作品,你可能不想重置分支,因为它实际上是在重写历史。在这种情况下,您确实可以恢复提交。Git,revert 有一个非常特殊的含义:使用反向补丁创建并提交以取消它。这样你就不会重写任何历史了。
6 f! }+ b5 z. L4 h
    # 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 commit: ]2 Y8 I9 I/ D% k/ G( l% q
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则