首页 > 解决方案 > VS Code Git:恢复到特定的提交

问题描述

我正在使用 VS Code 并想回到特定的提交 A。我目前在 C:

A -> B -> C

我最后一次提交是 C,现在我想将所有文件设置回提交 A 时的状态。如何在 VS Code 中做到这一点?(如果需要,在 VS Code 中使用命令行也可以)-

标签: gitvisual-studio-code

解决方案


所以你希望 B 和 C 一直在二级分支上?立即创建一个新分支(头在 C 处)以保留 B 和 C,但不要检查它;留在主人或不管这是什么。现在git reset --hard A

例子

我将在master上制作A,然后是B,然后是C:

$ echo "this is A" >> test.txt
$ git init
Initialized empty Git repository in /Users/mattmobile/Desktop/f/.git/
$ git add .
$ git commit -a -m "this is A"
[master (root-commit) 14cfab0] this is A
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt
$ echo "this is B" >> test.txt
$ git commit -a -m "this is B"
[master d55a780] this is B
 1 file changed, 1 insertion(+)
$ echo "this is C" >> test.txt
$ git commit -a -m "this is C"
[master 328183e] this is C
 1 file changed, 1 insertion(+)

让我们检查一下;是的,A然后B然后C:

$ git log
commit 328183e34767ed1bb06834e47d9bb3524e768546 (HEAD -> master)

    this is C

commit d55a780bcf1bda20ad7ceacce7c7c3777295fd59

    this is B

commit 14cfab017f3718bc7f3126e73aa187ec62b5d2a3

    this is A

现在我后悔了。如果只有 B 和 C 在他们自己的分支上mybranch,我可以回到 A 上的 master 并继续工作。好的:

$ git branch mybranch
$ git reset --hard 14cfab
HEAD is now at 14cfab0 this is A

所以现在mybranch在 C(并与父 A 一起保留 C 和 B)但master在 A,我可以继续工作。让我们证明一下。我将添加 D:

$ git status
On branch master
nothing to commit, working tree clean
$ echo "this is D" >> test.txt
$ git commit -a -m "this is D"
[master bf8a4d4] this is D
 1 file changed, 1 insertion(+)

我们得到了什么?

$ git log
commit bf8a4d478ce61a78de94619ffea1dc58d1c9a799 (HEAD -> master)

    this is D

commit 14cfab017f3718bc7f3126e73aa187ec62b5d2a3

    this is A

所以master由 A 组成,然后是 D。正是我们想要的。同时,B 和 C 仍然活着mybranch

$ git checkout mybranch
Switched to branch 'mybranch'
$ git log
commit 328183e34767ed1bb06834e47d9bb3524e768546 (HEAD -> mybranch)

    this is C

commit d55a780bcf1bda20ad7ceacce7c7c3777295fd59

    this is B

commit 14cfab017f3718bc7f3126e73aa187ec62b5d2a3

    this is A

推荐阅读