在被推后恢复合并

我执行的步骤:

我有两个分支1和2,

$git branch --Initial state
$branch1


$git checkout branch2
$git pull origin branch1 --Step1

我解决了冲突,做了一个

$git commit -m "Merge resolved"

那么

$git checkout branch1
$git merge branch2
$git push origin branch1

Now I realised that while being at step1, the auto merging removed some code and the change code was pushed. Now I want to go back to my initial state in order to revert any changes. Looking for some immediate help?

152936 次浏览

尝试使用 git reflog <branch>查找合并前分支的位置,使用 git reset --hard <commit number>恢复旧版本。

Reflog 将向您显示分支的旧状态,因此您可以将其返回到任何您喜欢的更改集。

在使用 git 重置时,请确保位于正确的分支中

要更改远程存储库历史记录,您可以执行 git push -f,但是不推荐这样做,因为有人已经下载了由您推送的更改。

您可以在 官方指南之后恢复合并,但是这会使 Git 错误地认为合并的提交仍然在目标分支上。

基本上你必须:

git revert -m 1 (Commit id of the merge commit)

The first option is the use of git revert.

git revert -m 1 [sha-commit-before-merge]

git revert将恢复更改,但将保留历史记录。因此,您将无法继续在同一个分支中工作,因为您再也看不到合并的分支和您的特性分支之间的实际差异。 也可以使用以下方法删除历史记录。当且仅当您是此刻唯一一个将更改推向分支的人时,请非常小心地执行此操作。

git reset --hard [sha-commit-before-merge]
git push [origin] [branch] --force

In my case, I merged my branch (say: my-branch) with another feature branch (feature-branch) but not master. 所以我的分行历史是这样的:

my-branch (before merge)


---master----m1----m2----m3---m4

将它与另一个在 master 上提交了 f1, f2feature-branch合并后,它变成了这样:

my-branch (after merge)


---master----m1----m2----f1----f2----m3---m4----mergecommit

这可能是因为在处理分支时,我在2次提交后从 master 进行了合并,或者2个分支中的一个可能没有更新到 master。 因此,在这种情况下,git revert -m 1不能正常工作,因为它让这些 f1f2提交之间。

The solution was simple, which will work in case of normal scenarios, where we don't have in-between commits:

git rebase -i HEAD~6

而不是6使用适当的数字基于多少过去的提交,你想要改变。 现在打开了 Vim 编辑器,只需将不需要的提交标记为 drop,并使用 :wq退出 核实日志:

git log --oneline

force push

git push -f

现在远程分支应该处于以前的状态。

As mentioned in another answer, the primary issue with doing a git revert on a merge is that git still thinks all the previous commits were merged (it only changes the code). If you attempt to merge that branch later on, you'll find those prior commits are missing.

更好的方法(显然是在与您的团队协商之后,这样他们就不会继续处理有问题的分支)是更早地提交 git reset。它不一定是一个硬重置,因为它只处理如何处理当前的工作变更,所以这部分取决于您。

You can also create a temporary branch from the previous commit if you would like to make changes there first before doing the reset. In that case you would reset to a commit on your temporary branch.

如果不从上游拉动,你将无法推动,但显然你不想拉动你试图恢复的变化。因此,您需要执行强制推送(或者使用租约强制推送,以便在此期间停止任何更改)。

旁注: 作为 VS Code 和 Git Graph 的粉丝,我发现强制推送很容易做到,只需右击本地分支标签名称并选择“ Push Branch...”,选择 Force 或 Force With Lease,选中 Set Upstream 框。