Hello,阳光柠檬! 养成记录笔记的好习惯

Git合并多个提交

2018-09-28
liukang
Git

git log -3

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

add text in second.txt

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

create second.txt

commit f6e45575484666245bb22d2d5d534bfex91f44c2
Author: lk
Date:   Mon Nov 28 12:51:13 2016 +0800

create one.txt

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

git rebase -i HEAD~2

会出现下面的提示

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
squash 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 -2查看

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

    create second.txt
    
    add text in second.txt

commit f6e45575484666245bb22d2d5d534bfex91f44c2
Author: lk
Date:   Mon Nov 28 12:51:13 2016 +0800

create one.txt

Comments

Content