江湖浪人 发表于 2018-1-15 10:10:55

git合并多个提交

git合并多个提交
[时间:2016-11] [状态:Open]
  
[关键词:git,git rebase,合并提交,commit]

0. 引言
  本文是关于Git提交记录修改的方法,主要是将多个提交记录合并为一个,然后提交。这里使用到git rebase(一般译为衍和),多数情况下推荐在未提交到远程仓库之前修改本地git提交记录格式时使用。
  
我遇到这个问题主要是因为实际提交中需要在多个分支之间切换,不希望在另一个分支上看到当前分支的多次提交,只希望将多次提交压合成一个提交,然后在另一个分支上直接git cherry-pick即可。

1. 合并多个提交
  为了美化commit history不择手段
  
首先,为了模拟实际git rebase效果,我们先在git上提交两个修改。git log如下:
  

commit e1a7dfa9dfea8e63ad079dba37c61d8e80ffbe1b  
Author: Tocy
  
Date:   Mon Nov 28 14:01:45 2016 +0800
  

  
add text in second.txt
  

  
commit c6e45575484666245bb22d2d5d534bfee91f44c6
  
Author: Tocy
  
Date:   Mon Nov 28 13:59:43 2016 +0800
  

  
create second.txt
  

  假设合并这两个提交,可以按照下面过程

git rebase -i HEAD~2
  可以先用man查看下git rebase的命令参数,这样会有如下提示:
  

pick c6e4557 create second.txt  
pick e1a7dfa add text in second.txt
  

  
# Rebase a71eba2..e1a7dfa onto a71eba2
  
#
  
# Commands:
  
#p, pick = use commit
  
#r, reword = use commit, but edit the commit message
  
#e, edit = use commit, but stop for amending
  
#s, squash = use commit, but meld into previous commit
  
#f, fixup = like "squash", but discard this commit's log message
  
#x, exec = run command (the rest of the line) using shell
  
#
  
# These lines can be re-ordered; they are executed from top to bottom.
  
#
  
# If you remove a line here THAT COMMIT WILL BE LOST.
  
#
  
# However, if you remove everything, the rebase will be aborted.
  
#
  
# Note that empty commits are commented out
  

  第一列是rebase具体执行的操作,其中操作可以选择,其中含义如下:


[*]选择pick操作,git会应用这个补丁,以同样的提交信息(commit message)保存提交
[*]选择reword操作,git会应用这个补丁,但需要重新编辑提交信息
[*]选择edit操作,git会应用这个补丁,但会因为amending而终止
[*]选择squash操作,git会应用这个补丁,但会与之前的提交合并
[*]选择fixup操作,git会应用这个补丁,但会丢掉提交日志
[*]选择exec操作,git会在shell中运行这个命令
  对比之前的两个提交提交,我觉得第一个提交可以保留,第二个合并到第一个就可以了。

将第二个pick改成squash或者s,然后保存退出。如下:
  

pick c6e4557 create second.txt  
s e1a7dfa add text in second.txt
  

此时git会自动将第二个提交合并到第一个提交,并弹出合并提示信息,如下:
  

# This is a combination of 2 commits.  
# The first commit's message is:
  

  
create second.txt
  

  
# This is the 2nd commit message:
  

  
add text in second.txt
  

  
# 请为您的变更输入提交说明。以 '#' 开始的行将被忽略,而一个空的提交
  
# 说明将会终止提交。
  
#
  
# 日期:Mon Nov 28 13:59:43 2016 +0800
  
#
  
# 变基操作正在进行中;至 a71eba2
  
# 您在执行将分支 'master' 变基到 'a71eba2' 的操作时编辑提交。
  
#
  
# 要提交的变更:
  
#   新文件:   second.txt
  
#
  

如果需要修改下提交信息,如果不需要直接保存退出即可。

此时我们已经完成了将两个提交合并为一个的处理,可以通过git log查看
  

commit 251d222ac45f3596943480bd5a7cc695b5d7d6e9  
Author: Tocy
  
Date:   Mon Nov 28 13:59:43 2016 +0800
  

  create second.txt
  add text in second.txt
  

  

总结
  注意本文仅仅介绍了我遇到的多个提交合并的问题,关于git rebase用法,建议参考Git Community Book 中文版-rebase和参考资料中的介绍。
  
多数情况下git rebase仅限在本地使用,也就是在提交到远程分支之前。

参考资料


[*]使用git合并多个提交
[*]git rebase简介(高级篇)
[*]git-rebase用法总结
[*]git-rebase(认真看,分析很到位)
页: [1]
查看完整版本: git合并多个提交