如何在不删除最新提交的情况下恢复到上一次提交



假设我有两个提交,我已经将它们推送到我的远程分支。

  • 提交A(2021年5月31日(
  • 提交B(2021年5月30日(

如何在不删除提交A的情况下恢复到提交B?我只想比较这两次提交的结果。

注意:不需要代码比较。我只想比较Commit A和Commit B 的输出

我强烈反对其他建议您使用git revert的答案。这实际上会还原Commit A引入的更改,并自行生成提交。

由于您想查看某个时间点的状态,因此可以直接签出Commit B,以便检查内容。然后签出原始分支以返回到最近的提交。

git checkout $HASH_OF_COMMIT_B   # now you are in a detached head state at commit B
git checkout $BRANCH             # now you are back at the tip of the branch (commit A)

许多工具可以让您直接查看两个引用之间的差异,而无需签出。在命令行上,这可以通过git diff:来完成

git diff $HASH_OF_COMMIT_A..$HASH_OF_COMMIT_B

如何在不删除提交A的情况下恢复到提交B?

您可以轻松使用git rebase -i <commit_hash>

  • 在提交B之前选择一个提交,即提交C

HEAD<-提交A<-提交B<-提交C

  • git rebase -i <commit_hash_commitC>
  • 上面的命令将在您的文本编辑器中列出如下所示的提交:
pick f7f3f6d Commit B
pick a5f4a0d Commit A
# Rebase 710f0f8..a5f4a0d onto 710f0f8
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
  • 删除表示提交B的行,然后保存并退出文本编辑器
  • Git将回放交互式编辑器中提到的所有提交,并将停止,这将完全删除Commit B

还原CommitB不会删除CommitA。它只会创建提交C,这将撤消您在委托B中所做的一切

git revert commit-b-hash
git revert <Commit B>

给定一个或多个现有提交,恢复相关补丁引入的更改,并记录一些记录这些更改的新提交。这需要您的工作树是干净的(没有来自HEAD提交的修改(。git-docs


但是,如果你只想看看两者之间的区别:

git diff <Commit B>..<Commit A>

显示工作树和索引或树之间的更改、索引和树之间的变化、两个树之间的改变、合并引起的改变、两个blob对象之间的改变或磁盘上两个文件之间的改变。git-docs

您可以执行交互式重基,删除不需要的提交,并在删除分支上执行硬推。

git rebase -i     //opens interactive rebasing window
pick #commitID2 My commit 2
pick #commitID1 My commit 1    <- To unpick/remove this commit, using editor remove 
line->
save the window.
git push origin branchname -f 

相关内容

  • 没有找到相关文章