在 Rebase 期間壓扁提交

提交可以在 git rebase 期間被壓扁。在嘗試以這種方式壓縮提交之前,建議你瞭解變基。

  1. 確定要重新繫結的提交,並記下其提交雜湊值。

  2. git rebase -i [commit hash]

    或者,你可以鍵入 HEAD~4 而不是提交雜湊,以檢視最新提交以及最新提交之前的 4 次提交。

  3. 在執行此命令時開啟的編輯器中,確定要壓縮的提交。用 squash 替換這些行開頭的 pick,將它們壓縮到上一次提交中。

  4. 選擇要壓縮的提交後,系統將提示你編寫提交訊息。

記錄提交以確定重新定位的位置

> git log --oneline
612f2f7 This commit should not be squashed
d84b05d This commit should be squashed
ac60234 Yet another commit
36d15de Rebase from here
17692d1 Did some more stuff
e647334 Another Commit
2e30df6 Initial commit

> git rebase -i 36d15de

此時,你選擇的編輯器會彈出,你可以在其中描述你要對提交執行的操作。Git 在評論中提供幫助。如果你原樣保留它,那麼什麼都不會發生,因為每次提交都將保留,並且它們的順序將與 rebase 之前的順序相同。在此示例中,我們應用以下命令:

pick ac60234 Yet another commit
squash d84b05d This commit should be squashed
pick 612f2f7 This commit should not be squashed

# Rebase 36d15de..612f2f7 onto 36d15de (3 command(s))
#
# 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

寫提交訊息後的 Git 日誌

> git log --oneline
77393eb This commit should not be squashed
e090a8c Yet another commit
36d15de Rebase from here
17692d1 Did some more stuff
e647334 Another Commit
2e30df6 Initial commit