[教學] git-23 修改歷史紀錄 - 討論區

[教學] git-23 修改歷史紀錄

文章瀏覽次數 1225 文章回覆數 0

特種兵

特種兵圖像(預設)

2020-04-08 17:44:50

From:211.23.21.202

之前我們分享過使用 --amend 來修改上一次的 commit 提交訊息。

但如果我們想修改的是更之前的提交訊息,且可能不只一筆的話該怎麼做?

我們要利用 rebase 指令的互動模式,這個指令可以用另一種方式來合併分支,在這裡,我們先把焦點放在互動模式上。

# 先看一下最近 5 個 commit
$ git log --oneline -5                                                          
 8436216 (HEAD -> master) 保留 new_test 的版本                                   
 2a621b5 我也加了相同的 word 檔檔名進來                                          
 0ceca24 (new_test) 增加一個 word 檔                                             
 ca4c2fe Merge commit 'fa03700'                                                  
 fa03700 在 abc.txt 加了一行                                                     

我覺得第2個提交訊息不清楚,想要把當時加入哪個 word 檔的檔名補上去。

# 啟動 rebase 的互動模式,時間段是從現在到該版號之間的所有紀錄
# 他會跳出預設編輯器,列出這個區間段的所有 commit 紀錄
# 如果是 c 要合併到 b 那我們就設定不會更動到的 a 
$ git rebase -i fa03700

pick 71188bf 在 ooqq.txt 新增第二與三行
pick 2a621b5 我也加了相同的 word 檔檔名進來
pick 0ceca24 增加一個 word 檔

# Rebase fa03700..8436216 onto fa03700 (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# 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

pick 是保持原本的 commit 與訊息

reword 是修改該條 commit 的訊息

其他指令後面章節會介紹。

這時候我把要修改訊息的 commit 前面 pick 換成 reword 也可以只打 r 就好:

pick 71188bf 在 ooqq.txt 新增第二與三行
reword 2a621b5 我也加了相同的 word 檔檔名進來
pick 0ceca24 增加一個 word 檔

然後存檔離開。接著還是會在編輯器中,要你修改 commit 的內容,

修改好後存檔離開,這樣就完成了。

$ git log --oneline -1                                                          
 d7de1ff (HEAD -> master) 我也加了生活班232小時課表--0610.doc                    

其實使用 rebase 修改 commit 並不只是改字而已,被修改及之後的 commit 版號都會改變,

對 git 來說其實是之後的 commit 都重做了一遍。

如果後悔了可以使用 git reset --hard ORIG_HEAD 來回到還沒 rebase 的狀態。

ORIG_HEAD 是每次我們在做較危險動作時會產生的一個紀錄點,例如合併分支,刪除分支等等。

有點像是準備做危險動作時先留一份備份的感覺。

如果是處理到一半想放棄,就輸入 git rebase --abort