代码合并的时候,有时候合并后发现合并错了,需要回滚或重置
回滚merge其实有两种方式,一种是revert
,一种是reset
构造一个已经merge的分支,并准备撤销/回滚刚才的merge
mkdir git-revert-merge-commit
cd git-revert-merge-commit
git init
echo 'file1' > file1
git add . && git commit -m 'commit 1'
echo 'file2' > file2
git add . && git commit -m 'commit 2'
git checkout -b feature
echo 'file3' > file3
git add . && git commit -m 'feature - commit 1'
echo 'file4' > file4
git add . && git commit -m 'feature - commit 2'
git checkout master
echo 'file5' > file5
git add . && git commit -m 'commit 3'
echo 'file6' > file6
git add . && git commit -m 'commit 4'
git checkout master
git merge feature
revert的原理实际上就是提交一个反向变更,低消之前的变更。revert会保留所有的操作记录,历史变更和revert变更都会保存在历史中,可以从git log中看到
git revert d904008
➜ git-revert-merge-commit git:(master) git revert d904008
error: commit d904008ec11d364b674a720a9755bd5e247903fe is a merge but no -m option was given.
fatal: revert failed
回滚失败 no -m option was given
,这是因为merge是把两个分支合并到一起,回滚的话,就必须告诉git需要回滚到哪个个分支
commit d904008ec11d364b674a720a9755bd5e247903fe (HEAD -> master)
Merge: dd542b2 18b2194
Author: timxia <timxia@tencent.com>
Date: Wed Jun 9 13:29:10 2021 +0800
Merge branch 'feature'
commit dd542b2a254a27d1704fe4f9317fef7e3d99b2cb
Author: timxia <timxia@tencent.com>
Date: Tue Jun 8 20:01:41 2021 +0800
commit 4
commit 99acb1f6ddfbd2cdc2bb4a9e1073176c4d1a55e2
Author: timxia <timxia@tencent.com>
Date: Tue Jun 8 20:01:41 2021 +0800
commit 3
commit 18b2194719103f2917960268683b4d052b2eeec3 (feature)
Author: timxia <timxia@tencent.com>
Date: Tue Jun 8 20:01:37 2021 +0800
feature - commit 2
#省略了其他的commit...
从log(Merge: dd542b2 18b2194
)中可以看出来,dd542b2(master)是1,18b2194(feature)是2
所以回滚到master的-m参数值是1,命令是git revert d904008 -m 1
➜ git-revert-merge-commit git:(master) git revert d904008 -m 1
Removing file4
Removing file3
[master 2c32c27] Revert "Merge branch 'feature'"
2 files changed, 2 deletions(-)
delete mode 100644 file3
delete mode 100644 file4
git log --pretty=oneline
## 结果如下
2c32c27231cdceee676286038e3551913d324a04 (HEAD -> master) Revert "Merge branch 'feature'"
d904008ec11d364b674a720a9755bd5e247903fe Merge branch 'feature'
dd542b2a254a27d1704fe4f9317fef7e3d99b2cb commit 4
99acb1f6ddfbd2cdc2bb4a9e1073176c4d1a55e2 commit 3
18b2194719103f2917960268683b4d052b2eeec3 (feature) feature - commit 2
1203202401c84cdc2defd589e958355ef0574662 feature - commit 1
759fb3f3c740764563ab11a03fdf5a3ad13ed9b9 commit 2
d7757c8fb1c65449d4e436b1c9bc575f79a01ce5 commit 1
日志中可以看出来,虽然合并进来的分支内容都退回了,但是提交记录以及回滚记录都在
是重置代码到历史某一个提交点
git reset dd542b2
git log --pretty=oneline
## 执行结果如下,可以看出来,合并的commit都没有了
dd542b2a254a27d1704fe4f9317fef7e3d99b2cb (HEAD -> master) commit 4
99acb1f6ddfbd2cdc2bb4a9e1073176c4d1a55e2 commit 3
759fb3f3c740764563ab11a03fdf5a3ad13ed9b9 commit 2
d7757c8fb1c65449d4e436b1c9bc575f79a01ce5 commit 1
如果merge过程中(一般是有冲突需要解决),想取消,则执行命令
git merge --abort