git rebase 命令介紹
本文源自極客時間 《go 語言項目開發實戰 孔令飛》
git rebase 的使用場景:
git rebase 的最大作用是它可以重寫歷史。
我們通常會通過 git rebase -i
這個交互界面會首先列出給定
git rebase 支持的變更操作如下:
在上面的 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 會從上到下進行合並。