一般來說,要修改最近一次的 commit,常見的方式有:
- git revert & git commit:這個方式很直覺,直接 revert 回上一個版本,然後重新 commit,不過因為 revert 會連這次 commit 中的記錄也消掉,這樣太麻煩了,我只是想改個 commit message 而已啊!XD
- git commit –amend:這個可以直接翻譯成”重新修改最近這次 commit”,其相當於
$ git reset –soft HEAD^
$ … do something else to come up with the right tree …
$ git commit -c ORIG_HEAD
然而,對於要修改較舊的 commit,上面的做法可能就不適用了,據我所知目前的做法有兩種,第一種是使用 git rebase:
git rebase –interactive <after-this-commit-id>
這樣會跳出介面讓你選擇想要修改的 commit,選擇完畢後,會由舊到新依序停在每個你所選擇的 commit,然後利用
git commit –amend
來修改該次的 commit,再搭配
git rebase –continue
來繼續下一個選擇的 commit。這種做法很方便,也可以快速地達到目的,因為是用 rebase,修改 commit message 倒是還好,如果有修改到 content,可能就要注意一下 conflict & merge 的問題了。另外,這個方式對某個我試的結果,對於修改 first commit 會沒輒。這時候可能要使用另一種比較麻煩的做法了。
第二種做法是利用一個由要修改的 commit 產生一個 target commit (在另一個 branch 中),同樣搭配 git commit –amend 來修改,最後利用 git rebase 來覆蓋原本的 commit:
# tag the source commit so we can reference it
git tag source-commit <source-commit-id>
# checkout on its own branch
git checkout -b fake-branch source-commit
# amend the commit
git commit –amend
# after you changed the commit message, checkout the original branch
git checkout <original-branch>
# and rebase it onto the source commit
git rebase –onto fake-branch source-commit
# then nuke the temporary branch and tag we created
git branch -d fake-branch
git tag -d source-commit
就看情形使用了,大部份還是用第一種做法,不過一開始就把 commit message 寫好最省事 XD
0 Response to “Git – How to edit incorrect commit messages?”