Git批量修改歷史commit中的user.name 和user.email

峻峰飛陽發表於2019-04-10

1.克隆倉庫

注意引數,這個不是普通的clone,clone下來的倉庫並不能參與開發

git clone --bare https://github.com/user/repo.git
cd repo.git

2.命令列中執行程式碼

OLD_EMAIL原來的郵箱 
CORRECT_NAME更正的名字 
CORRECT_EMAIL更正的郵箱

將下面程式碼複製放到命令列中執行

git filter-branch -f --env-filter '
OLD_EMAIL="wowohoo@qq.com"
CORRECT_NAME="小弟調調"
CORRECT_EMAIL="更正的郵箱@qq.com"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

執行過程

Rewrite 160d4df2689ff6df3820563bfd13b5f1fb9ba832 (479/508) (16 seconds passed, remaining 0 predicted)
Ref 'refs/heads/dev' was rewritten
Ref 'refs/heads/master' was rewritten

3.同步到遠端倉庫

同步到push遠端git倉庫

git push --force --tags origin 'refs/heads/*'

我還遇到了如下面錯誤,lab預設給master分支加了保護,不允許強制覆蓋。Project(專案)->Setting->Repository 選單下面的Protected branches把master的保護去掉就可以了。修改完之後,建議把master的保護再加回來,畢竟強推不是件好事。

remote: GitLab: You are not allowed to force push code to a protected branch on this project.

當上面的push 不上去的時候,先 git pull 確保最新程式碼

git pull  --allow-unrelated-histories
# 或者指定分枝
git pull origin master --allow-unrelated-histories

相關文章