git rebase 命令介紹


git rebase 命令介紹

本文源自極客時間 《go 語言項目開發實戰 孔令飛》

git rebase 的使用場景:

  1. 修改 Commit Message
  2. 合並多個commit

git rebase 的最大作用是它可以重寫歷史。

我們通常會通過 git rebase -i 使用 git rebase 命令,-i 參數表示交互(interactive),該命令會進入到一個交互界面中,其實就是 Vim 編輯器。在該界面中,我們可以對里面的 commit 做一些操作,交互界面如圖所示:
image

這個交互界面會首先列出給定 之前(不包括,越下面越新)的所有 commit,每個 commit 前面有一個操作命令,默認是 pick。我們可以選擇不同的 commit,並修改 commit 前面的命令,來對該 commit 執行不同的變更操作。

git rebase 支持的變更操作如下:
image

在上面的 7 個命令中,squash 和 fixup 可以用來合並 commit。例如用 squash 來合並,我們只需要把要合並的 commit 前面的動詞,改成 squash(或者 s)即可。你可以看看下面的示例:

pick 07c5abd Introduce OpenPGP and teach basic usage
s de9b1eb Fix PostChecker::Post#urls
s 3e7ee36 Hey kids, stop all the highlighting
pick fa20af3 git interactive rebase, squash, amend

rebase 后,第 2 行和第 3 行的 commit 都會合並到第 1 行的 commit。這個時候,我們提交的信息會同時包含這三個 commit 的提交信息:

# This is a combination of 3 commits.
# The first commit's message is:
Introduce OpenPGP and teach basic usage
# This is the 2ndCommit Message:
Fix PostChecker::Post#urls
# This is the 3rdCommit Message:
Hey kids, stop all the highlighting

如果我們將第 3 行的 squash 命令改成 fixup 命令:

pick 07c5abd Introduce OpenPGP and teach basic usage
s de9b1eb Fix PostChecker::Post#urls
f 3e7ee36 Hey kids, stop all the highlighting
pick fa20af3 git interactive rebase, squash, amend

rebase 后,還是會生成兩個 commit,第 2 行和第 3 行的 commit,都合並到第 1 行的 commit。但是,新的提交信息里面,第 3 行 commit 的提交信息會被注釋掉:

# This is a combination of 3 commits.
# The first commit's message is:
Introduce OpenPGP and teach basic usage
# This is the 2ndCommit Message:
Fix PostChecker::Post#urls
# This is the 3rdCommit Message:
# Hey kids, stop all the highlighting

除此之外,我們在使用 git rebase 進行操作的時候,還需要注意以下幾點:

  • 刪除某個 commit 行,則該 commit 會丟失掉。
  • 刪除所有的 commit 行,則 rebase 會被終止掉。
  • 可以對 commits 進行排序,git 會從上到下進行合並。


免責聲明!

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



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