前言
在開始一個功能時,可能會在主線(master
) 開出新的分支(feature-x
) 出去進行,
我們在支線(feature-x
) 可能 commit 了好多次,
但是希望有一天併回去主線(master
)的時候可以只留下一個主要功能的 commit,
避免分支看起來非常雜亂
語法使用
commit-id 放你要要改寫的前一個點
直接上實例可能會比較了解
如圖可以看到這是我們目前分支狀況
(圖片的分支與平常使用的方向相反,愈下面愈新)
我們從 C2 切了一個新分支出來 feature-x
, 我要把 C3,C4,C5 合併回去 master
但是我希望合併回去時只有一個 commit,
我需要在feature-x
分支下
step 1:下指令 我要修改他們!
1
2
| git checkout feature-x
git rebase -i C2
|
⭐ 這邊很重要 ! 我們需要取用將他們合起來的前一個點 C2
當起點
step 2: 要怎麼修改他們呢
執行完後,會出現一個編輯介面:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| pick C3 feature - commit message aaaaaaa
pick C4 fix-abc
pick C5 fix-def
# Rebase C2..C5 onto C2
#
# 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
|
上面 pick 是你目前 commit 區間 C3,C4,C5
這邊 commit 順序與我們平常看的相反
- pick: 就是會保留這個 commit
- fixup: 就是會拿掉這個 commit
這兩個最常用,因為其他我也沒有使用過 🤣🤣🤣
因為我們只要保留一個 C3
所以我們將 C4,C5 的前面 pick
改成 f
1
2
3
| pick C3 feature - commit message aaaaaaa
f C4 fix-abc
f C5 fix-def
|
然後
儲存 !
step3: 完成了
完成後,分支就會長這樣

如此一來將 feature-x
合併回去 master
時,就會只看到一個 commit
step4: 合併回去 master
1
2
| git checkout master
git merge feature-x --no-ff
|
