我不小心在本地主分支上运行了gitmergesome_other_branch。我还没有将更改推送给origin master。如何撤消合并?


合并后,git状态显示:

# On branch master
# Your branch is ahead of 'origin/master' by 5 commits.

我如何撤销所有这些提交?


当前回答

它可以通过多种方式实现。

1) 中止合并

如果您处于错误合并(错误地使用了错误的分支)之间,并且希望避免合并,以便最新返回分支,如下所示:

git merge --abort

2) 将HEAD重置为远程分支

如果您从远程开发分支工作,可以将HEAD重置为远程分支上的最后一次提交,如下所示:

git reset --hard origin/develop

3) 删除当前分支,然后再次从远程存储库签出

考虑到您正在本地repo中开发分支,该分支与远程/开发分支同步,您可以执行以下操作:

git checkout master 
##to delete one branch, you need to be on another branch, otherwise you will fall with the branch :) 

git branch -D develop
git checkout -b develop origin/develop

其他回答

如果您的合并和相应的提交尚未被推送,您可以始终切换到另一个分支,删除原始分支并重新创建它。

例如,我意外地将一个开发分支合并到master中,并想撤消它。使用以下步骤:

git checkout develop
git branch -D master
git branch -t master origin/master

瞧!Master与原点处于同一阶段,您的错误合并状态将被清除。

到了这个问题,我们也希望恢复到与原点匹配(即,在原点之前没有提交)。进一步研究发现,有一个重置命令正是针对这一点:

git重置--硬@{u}

注意:@{u}是origin/master的简写。(当然,您需要远程存储库才能实现这一点。)

你必须改变你的头,当然不是你的,而是你的头。。。。

所以在回答之前,让我们添加一些背景,解释一下这个HEAD是什么。

首先,什么是头部?

HEAD只是对当前分支上当前提交(最新)的引用。在任何给定时间只能有一个HEAD。(不包括git工作树)

HEAD的内容存储在.git/HEAD中,它包含当前提交的40字节SHA-1。


分离式封头

如果您不在最近一次提交中,这意味着HEAD指向历史上的先前提交,它称为分离的HEAD。

在命令行上,它看起来像-SHA-1而不是分支名称,因为HEAD没有指向当前分支的末端

关于如何从分离的HEAD恢复的几个选项:


git校验

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

这将签出指向所需提交的新分支。此命令将签出到给定的提交。此时,您可以创建一个分支并从此开始工作。

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

数字刷新

您也可以始终使用reflog。git reflog将显示更新HEAD的任何更改,检查所需的reflog条目将将HEAD设置回该提交。

每次修改HEAD时,reflog中都会有一个新条目

git reflog
git checkout HEAD@{...}

这会让你回到你想要的承诺


git reset--hard<commit_id>

将你的头“移”回所需的位置。

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.

注:(自Git 2.7以来)您也可以使用git rebase--也可以不使用autostash。


git还原<sha-1>

“撤消”给定的提交或提交范围。重置命令将“撤消”给定提交中所做的任何更改。将提交带有撤销补丁的新提交,而原始提交也将保留在历史记录中。

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

此模式说明了哪个命令执行什么操作。正如您可以看到的那样,重置和签出修改HEAD。

对于较新的Git版本,如果您尚未提交合并,并且存在合并冲突,您可以简单地执行以下操作:

git merge --abort

来自man git merge:

只有在合并导致冲突后才能运行[This]。gitmerge--abort将中止合并过程并尝试重建合并前的状态。

最简单的机会,比这里说的任何事情都简单得多:

删除本地分支(本地,而不是远程),然后再次拉动它。这样,您将撤消主分支上的更改,任何人都将受到您不想推送的更改的影响。重新开始。