我不小心修改了我以前的提交。提交应该是独立的,以保留我对特定文件所做更改的历史记录。
有没有办法撤消最后一次提交?如果我做像git reset --hard HEAD^
这样的事情,第一次提交也会撤消。
(我还没有推到任何远程目录)
您需要做的是创建一个新的提交,其具有与当前HEAD
提交相同的详细信息,但父级为HEAD
的先前版本。 git reset --soft
将移动分支指针,以便下一次提交发生在当前分支头现在的不同提交之上。
# Move the current head so that it's pointing at the old commit
# Leave the index intact for redoing the commit.
# HEAD@{1} gives you "the commit that HEAD pointed at before
# it was moved to where it currently points at". Note that this is
# different from HEAD~1, which gives you "the commit that is the
# parent node of the commit that HEAD is currently pointing to."
git reset --soft HEAD@{1}
# commit the current tree using the commit details of the previous
# HEAD commit. (Note that HEAD@{1} is pointing somewhere different from the
# previous command. It's now pointing at the erroneously amended commit.)
git commit -C HEAD@{1}
如果您已将提交推送到远程,然后错误地修改了该提交的更改,这将解决您的问题。发出git log
以在提交之前找到SHA。 (这假定远程命名为origin)。现在使用该SHA发出这些命令。
git reset --soft <SHA BEFORE THE AMMEND>
#you now see all the changes in the commit and the amend undone
#save ALL the changes to the stash
git stash
git pull origin <your-branch> --ff-only
#if you issue git log you can see that you have the commit you didn't want to amend
git stash pop
#git status reveals only the changes you incorrectly amended
#now you can create your new unamended commit
使用ref-log:
git branch fixing-things HEAD@{1}
git reset fixing-things
然后,您应该只在您的工作副本中进行所有先前修改的更改,并且可以再次提交
要查看以前索引的完整列表,请键入git reflog
通过以下方式查找修改的提交:
git log --reflog
注意:为了清楚起见,您可以添加--patch
以查看提交的正文。与git reflog
相同。
然后将HEAD重置为任何先前的提交,只需通过以下方式:
git reset SHA1 --hard
注意:将SHA1替换为您的实际提交哈希。另请注意,此命令将丢失所有未提交的更改,因此您可以先将其存储。或者,使用--soft
来保留最新的更改,然后提交它们。
然后樱桃挑选你需要的其他提交:
git cherry-pick SHA1
您可以随时拆分提交,来自manual
也许可以使用git reflog
在修改之前和修改之后获得两次提交。
然后使用git diff before_commit_id after_commit_id > d.diff
在修改之前和修改之后得到差异。
接下来使用git checkout before_commit_id
返回到提交之前
最后使用git apply d.diff
来应用你所做的真正改变。
这解决了我的问题。
可能值得注意的是,如果您仍然在编辑器中使用提交消息,则可以删除提交消息,它将中止git commit --amend
命令。
你可以在下面撤消你的git commit —amend
git reset --soft HEAD^
git checkout files_from_old_commit_on_branch
git pull origin your_branch_name
====================================
现在您的更改与之前一样。所以你完成了对git commit —amend
的撤消
现在你可以做git push origin <your_branch_name>
,推进分支机构。
差不多9年了,但没有看到这种变化提到完成同样的事情(这是其中一些的组合,类似于最佳答案(https://stackoverflow.com/a/1459264/4642530)。
搜索分支上的所有分离头
git reflog show origin/BRANCH_NAME --date=relative
然后找到SHA1哈希
重置为旧SHA1
git reset --hard SHA1
然后把它推回去。
git push origin BRANCH_NAME
完成。
这将使您完全恢复到旧提交。
(包括先前覆盖的分离提交头的日期)
git branch temp HEAD@{1}
git reset temp
git status
git reset myfile1.js
(等)git commit -C HEAD@{1}