是否有方法恢复提交,以便我的本地副本保留该提交中所做的更改,但它们在我的工作副本中成为未提交的更改?回滚提交会将您带到上一次提交—我想保留所做的更改,但我将它们提交到了错误的分支。

这并没有被推动,只是被承诺了。


当前回答

2020简单方法:

git reset <commit_hash>

要保留的上次提交的提交哈希。

其他回答

如果您推动了更改,则可以撤消更改并将文件移回后台,而无需使用其他分支。

git show HEAD > patch
git revert HEAD
git apply patch

它将创建包含最后分支更改的修补程序文件。然后恢复更改。最后,将补丁文件应用于工作树。

撤消上次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

有很多方法可以做到这一点,例如:

如果您尚未公开提交:

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

请确保在单独的文件夹中运行这些命令之前备份您的更改

git签出分支名称

在分支机构结账

git merge—中止

中止合并

git状态

中止合并后检查代码的状态

git reset--硬原点/分支名称

这些命令将重置您的更改,并将代码与branchname(branch)代码对齐。

对于这种情况:“这还没有被推送,只是提交了。”-如果你使用IntelliJ(或另一个JetBrains IDE),但你还没有推送更改,那么你可以做下一步。

转到版本控制窗口(Alt+9/Command+9)-“日志”选项卡。右键单击上次提交之前的提交。将当前分支重置为此处pick Soft(!!!)按下对话框窗口底部的重置按钮。

完成。

这将“取消提交”您的更改,并将您的git状态返回到上次本地提交之前的状态。您不会丢失所做的任何更改。