Git 修改所有提交用户的用户名和邮件

Author:Gao
Created At:2022-04-05

操作原理

使用git filter-branch重写提交历史

执行方式

设置脚本:

# 设置git alias 方便操作
git config --global alias.change-commits '!'"f() { VAR=\$1; OLD=\$2; NEW=\$3; shift 3; git filter-branch --env-filter \"if [[ \\\"\$\`echo \$VAR\`\\\" = '\$OLD' ]]; then export \$VAR='\$NEW'; fi\" \$@; }; f"

# 更换名字
git change-commits GIT_AUTHOR_NAME "old name" "new name"

# 更换邮箱
git change-commits GIT_AUTHOR_EMAIL "old@email.com" "new@email.com" HEAD~10..HEAD

### git config
### change-commits="!f() { VAR=$1; OLD=$2; NEW=$3; shift 3; git filter-branch --env-filter \"if [[ \\\"$`echo $VAR`\\\" = '$OLD' ]]; then export $VAR='$NEW'; fi\" \$@; }; f"


或者使用commit-filter

git filter-branch --commit-filter '
      if [ "$GIT_AUTHOR_EMAIL" = "wrong_email@wrong_host.local" ];
      then
              GIT_AUTHOR_NAME="Your Name Here (In Lights)";
              GIT_AUTHOR_EMAIL="correct_email@correct_host.com";
              git commit-tree "$@";
      else
              git commit-tree "$@";
      fi' HEAD
# 修改脚本可以一次修改多个名称

如果运行多次,会出现错误

A previous backup already exists in refs/original/ In that case, re run it, with the new email, and add a -f before the --commit-filter.

这需要执行

# 删除backup
git update-ref -d refs/original/refs/heads/master
# 恢复backup
git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch Rakefile' HEAD

更复杂的配置, 需要关联tags

#!/bin/bash

git filter-branch --env-filter '

OLD_EMAIL="oldEmail@xxx-MacBook-Pro.local"
CORRECT_NAME="yourName"
CORRECT_EMAIL="yourEmail"

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