首页 > 解决方案 > 如何回到git?

问题描述

这是我的git log样子-

Nikhil@admin-PC MINGW32 ~/Desktop/facebook by nick/Addmie/nodejs (messageadded)
$ git log
commit fcf7a0bf45dffdf2da197f84b1b3e4c21715b5f1 (HEAD -> messageadded, origin/messageadded)
Author: codewithnick <nikhilsingh526452@gmail.com>
Date:   Fri Jun 19 00:02:46 2020 +0530

    i have added the message feature it is not live chat yet]

commit 1e5fb40e7deb0787cd8be83b28f39f5acc06b8bf (origin/profileadded, profileadded, ajaxadded)
Author: codewithnick <nikhilsingh526452@gmail.com>
Date:   Sat Jun 13 23:57:23 2020 +0530

    i have seprated profiles

commit 1f8440134b0147efd454b966ffc464ff5843f51e (origin/ajaxadded, exploreadded)
Author: codewithnick <nikhilsingh526452@gmail.com>
Date:   Sat Jun 6 00:37:30 2020 +0530

    6/6/2020 12:37

message added在分支中最后一次提交后,我在代码中犯了一些错误。如何删除工作目录中的所有更改并返回到过去提交的时间?

标签: gitgithubgitlab

解决方案


Git 为您提供了相当多的选项来解决这个问题

暂时切换到不同的提交

如果您想暂时返回到特定的提交。只是尝试一下。您所要做的就是检查所需的提交:

# This will detach your HEAD, that is, leave you with no branch checked out:
git checkout <hash>

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

git checkout -b old-state <hash>

要回到你所在的位置,只需再次检查你所在的分支。(如果您进行了更改,就像在切换分支时一样,您必须酌情处理它们。您可以重置以丢弃它们;您可以存储、结帐、存储弹出以随身携带;您可以提交如果你想在那里有一个分支,他们可以去那里的一个分支。)

硬删除未发布的提交

如果您想严格覆盖您的更改:

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

# Alternatively, if there's work to keep:
git stash
git reset --hard <hash>
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:
git revert a867b4af..0766c053 

# 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.
git commit

一个有用的链接是讨论还原的git-scm.com 部分。


推荐阅读