Git - 如何變更 commit author

在軟體開發的世界中,Git 是一個極為重要的版本控制工具,用來追蹤和管理你的程式碼更動。

有時候,我們可能需要修改之前的 commit author 訊息,可能是因為作者名字錯誤拼寫,或者需要把 commit 歸屬給正確的人,或是不小心把公司 mail commit 進去

在這篇文章中,我們將學習如何在 Git 中變更 commit author。

變更最後一個 commit 的 author

如果你只是想要修改最後一個 commit 的 author,可以使用 --amend 參數來達成。image 66

1
git commit --amend --author="Author Name <New Email>"

變更多個 commit 的 author

如果你想要修改多個 commit 的 author,你可以使用 git filter-branch 這個指令來達成。

不過在那之前,也許你也會想知道到底有哪些 mail 會被 commit 進去,你可以使用下面這個指令來查詢:

1
git log --format='%aN <%aE>' | sort -u

接著,我們就可以使用 git filter-branch 來變更 commit author 了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash

# 設置新的 commit author 名稱和信箱
NEW_NAME="CodingMan"
NEW_EMAIL="hihi@gamail"

# 設置要搜尋的舊信箱
OLD_EMAIL_PATTERN="hihihihihi@gamail"

# 使用 git filter-branch 命令修改 author
git filter-branch --env-filter '
if [[ $GIT_AUTHOR_EMAIL == "'"$OLD_EMAIL_PATTERN"'" ]]; then
GIT_AUTHOR_NAME="'"$NEW_NAME"'"
GIT_AUTHOR_EMAIL="'"$NEW_EMAIL"'"
GIT_COMMITTER_NAME="'"$NEW_NAME"'"
GIT_COMMITTER_EMAIL="'"$NEW_EMAIL"'"
fi
' --tag-name-filter cat -- --all

# 顯示檢查結果
echo "檢查結果:"
git log --format='%aN <%aE>' | sort -u

你可以使用上面 git log --format='%aN <%aE>' | sort -u 來反覆確認 commit author 是否如你所想像地修改了。

最後,記得使用 git push --force 來強制推上去。

1
git push origin --force --all

☺️

也許你也會想看看