是否有方法恢复提交,以便我的本地副本保留该提交中所做的更改,但它们在我的工作副本中成为未提交的更改?回滚提交会将您带到上一次提交—我想保留所做的更改,但我将它们提交到了错误的分支。
这并没有被推动,只是被承诺了。
是否有方法恢复提交,以便我的本地副本保留该提交中所做的更改,但它们在我的工作副本中成为未提交的更改?回滚提交会将您带到上一次提交—我想保留所做的更改,但我将它们提交到了错误的分支。
这并没有被推动,只是被承诺了。
当前回答
对我来说,大多数情况下,当我将更改推到错误的分支并在稍后实现时,就会发生这种情况。大多数情况下,以下内容都有效。
git revert commit-hash
git push
git checkout my-other-branch
git revert revert-commit-hash
git push
恢复提交(创建并)签出其他分支还原还原
其他回答
有很多方法可以做到这一点,例如:
如果您尚未公开提交:
git reset HEAD~1 --soft
就是这样,提交更改将在工作目录中,而最后一次提交将从当前分支中删除。参见git重置手册
如果您确实公开推送(在名为“master”的分支上):
git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) )
恢复正常提交并推送
git checkout master
git revert a8172f36 #hash of the commit you want to destroy
# this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history)
git push origin master
现在,如果您希望在工作副本中进行本地更改时进行这些更改(“以便本地副本保留该提交中所做的更改”),只需使用--no commit选项还原还原提交:
git revert --no-commit 86b48ba (hash of the revert commit).
我制作了一个小例子:https://github.com/Isantipov/git-revert/commits/master
从2021起,谷歌同僚的最新更新。
如果您是VSCode用户,这里有一种现代的方法来撤消上次提交。
转到左侧的“源代码管理”选项卡(快捷键:Ctrl+Shift+G G)。按在circlish更新图标的左侧。请参阅下面的屏幕截图:导航到“提交”,然后导航到“撤消上次提交”。下面是一张截图:
它所做的只是恢复您的存储库,就像提交之前一样,您的更改保持不变。
撤消上次Git提交的最简单方法是使用以下选项之一执行Git reset命令
软的坚固的混合的
假设您添加了两次提交,并且希望撤消最后一次提交
$ git log --oneline
45e6e13 (HEAD -> master) Second commit
eb14168 Initial commit
–soft选项撤消上次提交并保留对文件所做的更改
$ git reset --soft HEAD~1
$ git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: file.html
$ git log --oneline
eb14168 (HEAD -> master) Initial commit
–hard选项撤消上次提交并放弃工作目录和索引中的所有更改
$ git reset --hard HEAD~1
$ git status
nothing to commit, working tree clean
$ git log --oneline
eb14168 (HEAD -> master) Initial commit
--混合选项撤消最后一次提交并将更改保留在工作目录中,但不保留在索引中
$ git reset --mixed HEAD~1
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file.html
no changes added to commit (use "git add" and/or "git commit -a")
$ git log --oneline
eb14168 (HEAD -> master) Initial commit
2020简单方法:
git reset <commit_hash>
要保留的上次提交的提交哈希。
如果您推动了更改,则可以撤消更改并将文件移回后台,而无需使用其他分支。
git show HEAD > patch
git revert HEAD
git apply patch
它将创建包含最后分支更改的修补程序文件。然后恢复更改。最后,将补丁文件应用于工作树。