immwind

长风

life, the programming and everything

使用 filter-repo 修改 git 提交記錄

前兩天發現有個專案的 git 郵箱寫錯了,趁今天稍微空些準備祭出祖傳的腳本進行修改,誰知出現提示: "git-filter-branch has a glut of gotchas generating mangled history rewrites. Hit Ctrl-C before proceeding to abort, then use an alternative filtering tool such as git filter-repo instead."。既然有新的命令 (方式) 自然要嘗試一般。

介紹#

git-filter-repo 是一個使用 [[Python]] 編寫,用於過濾和轉換 [[git]] 儲存庫歷史記錄的工具。可以對提交記錄進行各種操作,如刪除、重寫提交歷史、拆分儲存庫等。

安裝#

macOS 可以通過 [[Homebrew|brew]] 安裝:

brew install git-filter-repo

或是使用 [[pip]] 安裝:

pip3 install git-filter-repo

當然也可以直接從倉庫下載源文件運行,安裝的好處是可以結合到 git 命令中使用。

使用#

這裡主要是對歷史提交的郵箱信息進行修改:

git filter-repo --email-callback "return email.replace(b'old@email.com', b'new@email.com')"

另一種方式支持同時修改郵箱和姓名 (多個):

git filter-repo --mailmap mailmap

對應 mailmap 文件內容:

<new@email.com> <old@email.com>
new_name <new@email.com> old_name <old@email.com>

注:

  • --mailmap 中 <> 符號是必須的
  • --email-callback 和 --mailmap 兩種方式的郵箱順序不一樣

修改完成後 push 如果出現: "fatal: No configured push destination" 提示,需要先重新設置遠程倉庫:

git remote add origin <url>
git push --set-upstream origin master -f

問題#

在本機修改並 push 後,在伺服器上執行 pull 時提示:

hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint: 
hint:   git config pull.rebase false  # merge (the default strategy)
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint: 
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.

嘗試加 -f 和按提示操作之後也沒辦法解決,索性直接把 .git 目錄刪除,重新 clone 後拷貝過來後,提交記錄總算一致。

資訊#

環境#

  • Python 3.10.10
  • GitHub 2.39.2
  • git-filter-repo 2.38.0
  • System: macOS 13.4.1

參考#

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。