Git如何恢复到某个提交,但保留我所做的所有提交



假设我提交了A-B-C-D-E-F。请注意,所有提交都已向上游推送。

我希望恢复到提交D,但也希望在分支中保留提交E和F。

所以我想做的是创建一个commit G,它将具有与D相同的内容。最后,我的分支将看起来像a-B-C-D-E-F-G,其中D=G。

我该怎么做?

您只需要获取D的确切内容,并使用该内容创建一个提交:

# choose a. or b. :
# a. 'git restore' was added for this purpose in version 2.25,
#    and has options which are more explanatory (readable at least) :
git restore --source D --staged --worktree -- .
# b. for older gits, or for people enjoying more obscure commands, there is 'git read-tree' :
git read-tree D
# after that :
# confirm that the content you expect is staged, and commit :
git status
git commit

有一句话需要注意:带有--worktree选项的git restore可以删除文件,并放弃尚未存储在git中的文件中的修改,就像git reset --hard一样。

建议在干净的工作树上使用此命令,或者至少检查是否可以丢弃当前的修改。

最新更新