修改歷史的操作,原理上都是通過變基(rebase)實現的。
因爲發生了修改,則每個涉及的 commit 都會計算出新的 SHA-1 校驗和。
不使用 --force
選項,最好**不要修改已經推送到遠端的 commit!**這樣會與其他工作者產生衝突。
摘錄自官方文檔 Git v2 重寫歷史
修改最後一次 commit
只對最後一次 commit 做修改是比較方便的。
$ git commit --amend
這個命令會使用當前暫存區的內容,覆蓋最後一次的 commit,還允許你修改 commit 附帶的 message。
修改多個 commit
通過交互式的變基操作 git rebase -i
可以在任何想要修改的 commit 處暫停,修改後再繼續。
$ git rebase -i HEAD~3
這是一個變基命令,在你確認變基後 HEAD~3..HEAD
範圍內的每一個提交都會被重寫,無論你是否修改過它。
假設此時的 git log
是
4 310154e fixed typo
3 f7f3f6d updated README
2 a5f4a0d added LICENSE
1 b85f921 init
上文的命令會打開文本編輯器,展示如下的列表
pick a5f4a0d added LICENSE
pick f7f3f6d updated README
pick 310154e fixed typo
# Rebase b85f921..310154e onto b85f921
#
# 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
格式爲 <command> <commit> <message>
。
命令有短長兩種寫法
p, pick
正常提交該 commit,繼續變基r, reword
提交該 commit,但重新編輯 message,編輯後繼續變基e, edit
提交該 commit,提交後暫停變基,使用戶可以修改s, squash
合併該 commit 到前一個 commit,並重新編輯 message,編輯後繼續變基f, fixup
合併該 commit 到前一個 commit,使用前一個 commit 的 message,合併後繼續變基x, exec
將本行之後部分視爲 shell 命令執行
變基命令非常靈活,你可以在文本編輯器中改變 commit 的順序,刪除 commit 或者引入其他 commit,只要使得編輯後的變基操作列表能夠正常運行即可。
因爲 edit 命令而暫停了變基時,你可以執行各種操作,比如:
git commit --amend
修改暫停前的最後一次 commitgit reset HEAD^
撤銷最後一次 commit 到暫存區,再分次提交
修改妥當後,輸入 git rebase --continue
繼續變基。