Git Rebase合并提交

Git rebase命令合并多次提交以及将一个修改提交到过去的方式

# 背景

在开发中经常碰到的问题:1. 对同一个大功能进行了多次修改导致多次提交;2.多次提交过后,发现某一次提交中有bug,需要另外起一次commit进行修复的问题。这两种情况都会显得整个提交记录非常臃肿丑陋,且容易打乱commit记录。导致后续复盘时commit记录混乱。最近我通过和大模型对话及在搜索引擎搜索,掌握了使用git rebase命令改正这两个问题的方法,特此记录

# 使用限制

只能对于处于本地分支,还没有push到远程分支的修改有效。如果已经推送到了远程分支,或者同时有多个在修改一个分支,不建议使用以下方法修改commit记录。修改后与线上仓库中内容不一致无法push,如果强行使用git push –force等方式push容易导致整个仓库冲突。

# 用法一: git rebase 合并提交

适用于多次提交针对同一个功能开发,希望将其合并为一个提交的

# 步骤:查看提交记录

1
git log

假设输出的结果为:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
commit: hash1
    feature: add user system
    
commit: hash2
    feature: add user system
    
commit: hash3
    feature: add user system
    
commit: hash4
    feature: add gateway

这里我们的最近第1到第3个commit其实都是在进行同一个工作,因此我们会希望将其合并

# 步骤2:使用git rebase命令

1
git rebase -i {hash}

这个命令中的hash,指的是到第几个hash(不包括这个hash)。因为我们希望的是合并最近三个commit,因此我们使用的命令应当为

1
git rebase -i hash4

# 步骤3:挑选并合并

使用rebase命令后,会弹出一个命令框,大致格式为

1
2
3
pick hash3 feature: add user system
pick hash2 feature: add user system
pick hash1 feature: add user system

这里我们需要保存一个,因此我们取我们需要的那一个提交,将其保留为pick,另外两个提交改为squash。然后保存并退出编辑器,让git进行后续指令

后面会再弹出一个编辑框,选择需要保存的commit信息。我们编辑完信息,进行保存就可以

注意:如果使用vscode或jetbrain系列编辑器进行操作,会弹出适配的ui编辑框进行git rebase操作。如果有配置对应的编辑器,非常推荐使用编辑器挑选git rebase信息!

# 步骤4:检查并完成

可以使用git log检查完成git rebase完成后的commit信息,可以看到我们需要的多次提交被合并为了一次。确认无误后就可以完成这一次修改了。

1
2
3
4
5
commit: hash5
    feature: add user system
    
commit: hash4
    feature: add gateway

# 用法二: git rebase将将工作区改动追加到某次提交

适用于在多次提交不同功能后,发现之前的某一次commit存在bug,想在这个commit中添加一个修改。这种情况下,也可以使用git rebase操作

假设我们的commit log如下,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
commit: hash1
    feature: 优化 mysql 查询语句
    
commit: hash2
    feature: add redis cache
    
commit: hash3
    feature: add user system
    
commit: hash4
    feature: add gateway

并且我们发现在hash3对应的commit中,缺少了一些代码造成了bug,就可以按照如下方式进行改动追加到某次提交

  1. 保存工作区中的改动到stash中
    1
    2
    
    git add .
    git stash
    
  2. 将git head移动到需要更改的commit的前一个commit上。这里我们依旧是使用hash4,我们才能修改hash3
    1
    
    git reabse {hash4} --interactive
    
    找到需要更改的commit,将行首的pick改成edit,保存并退出
  3. 还原stash中的工作区改动git stash pop
  4. 将改动添加到暂存 git add .
  5. 通过amend方式提交改动到旧commit上,这里就对应例子中的hash3
    1
    
    git commit --amend --no-edit
    
  6. 完成rebase,将head移到最新commit
    1
    
    git rebase --continue
    
  7. 可能出现冲突解决
    1
    2
    3
    
    git add.
    git commit --amend
    git rebase --continue
    

# 总结

灵活的使用git rebase合并无用或重复提交,可大幅度提升commit log可读性。在多人合作的开发中还是非常有用的

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计