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僅限在本地使用,也就是在提交到遠程分支之前。

參考資料

  1. 使用git合並多個提交
  2. git rebase簡介(高級篇)
  3. git-rebase用法總結
  4. git-rebase(認真看,分析很到位)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM