likes
comments
collection
share

合并多个Commits,请注意!

作者站长头像
站长
· 阅读数 3

合并多个Commits

我们提交Pull Request的时候有时候并不是一个Commit就完成的,往往会做一些修改,然后再提交Commit,通常会走多轮,到最后就可能会有多个Commit,这时候往往需要合并这些Commits为一个,然后Manager帮你Merge。这时候我们就需要使用git rebase了。这里我并不打算详解rebase,这是Git book做的事,这里只是记录一下自己做的一个过程。

关于rebase可以参看这几篇文章:

首先git log查看需要合并的Commits,比如如下形式:

commit 3ade56efc466c093d7e8e25c520293cesedc96cc
Author: xxx
Date:   Wed Mar 1 12:31:10 2017 +0800

    Commit Message 4

commit 546ffc32692d3f935feb9b04d6ecb66feda9560b
Author: xxx
Date:   Mon Feb 20 15:28:40 2017 +0800

    Commit Message 3

commit f48b8644013c23f132c3fe72f8cc38ea288e6f3d
Author: xxx
Date:   Thu Feb 9 13:52:39 2017 +0800

    Commit Message 2

commit fe72f8cc38ea288e6c3fe72f8cc38ea288e6f3de
Author: xxx
Date:   Thu Feb 9 10:12:39 2017 +0800

    Commit Message 1

比如说我们需要合并Commit 2-4这三个提交,我们运行

git rebase -i <SHA-1 of Commit 1>  # -i后面的参数为最后一个不需要合并的Commit,这里为Commit 1

然后出现交互框,出现三个pick

pick ... Commit Message 2
pick ... Commit Message 3
pick ... Commit Message 4

我们将后两个pick改成squash,即:

pick ... Commit Message 2
squash ... Commit Message 3
squash ... Commit Message 4

这里两个操作的区别是:

  • pick的意思是要会选择合并到这个commit
  • squash(挤压)的意思是这个commit会被合并到前一个commit

然后输入新的Commit Message,保存,即合并成功,最后看只剩一个Commit了。最后Push到remote,这时会提示版本不合,因为本地这个进行了合并后,已经比remote老了,这时只需强推即可:

git push -f <upstream> <localbranch>:<remotebranch>

最后,多个提交就变成了一个提交,可以被merge了。

后悔药

注意,如果出现了什么不想看到的结果或者操作错误,可以使用

git rebase --abort

进行挽救,即可恢复到rebase之前的状态。

简易方法

如果只需合并两个Commit,且又是最近的两个Commit,其实可以更简单地使用:

git reset --soft HEAD^1
git commit --amend

来解决。