您的位置:首页 > 其它

如何撤销Git的一次分支合并操作

2016-02-02 19:35 573 查看

合并分支的操作rebase或者merge

使用git多人协作开发同一个项目时,多人协同编写修改同一份代码时,各自在自己的分支上修改编辑代码;最终都需要保存提交到代码的主分支,这里会涉及到分支间的合并操作一般为:

git merge masterbranch
git rebase masterbranch


这两个操作都是将当前所在的分支与masterbranch分支合并;具体的区别或者合并的具体解释该篇博文暂不介绍。

如何快速安全的撤销一次合并操作?

如下当前处于开发分支developing,远端主分支为master:



两个分支各有两次提交:



在developing分支执行git merge master操作:



在这个前提下,假如突然发现合并错分支想撤销此次合并,这里介绍两个方案:

- 危险操作的保护ORIG_HEAD

根据一个stack overflow的大神的原话解释:

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which “git commit” would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called “detached HEAD”, and can be understood as being on unnamed, anonymous branch.

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

大概就是git在你进行一些比较大风险性操作的时会将ORIG_HEAD指向该危险操作的起点,相当游戏中自动记录了一个复活点在ORIG_HEAD。所以在rebase后者merge操作后,如果你并没有进行任何其它操作可以直接使用

git reset --hard ORIG_HEAD




快速撤销此次合并,非常方便好用。

- 使用git reflog实现神一般的回退

如果合并之后已经做了一些操作或者想做一些更细致的回退操作使用git reflog来查找你需要的“复活点”,事实上git会标记并记录你大部分的操作,相当于随时给你做了相当多的游戏存档,在你需要时可以选择任意存档来重新开始,但是可能会丢失掉一些修改,不了解reset操作的童鞋请先补习慎重使用。

git reset --hard HEAD@{8}




从图中可以看到,大部分的HEAD@{*}记录了你重要的提交/切换/合并等操作的点,找到你需要回退的点,执行reset操作即可实现回退。

参考的stack overflow:

http://stackoverflow.com/questions/964876/head-and-orig-head-in-git

http://stackoverflow.com/questions/134882/undoing-a-git-rebase/135614#135614
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: