批量更改远程仓库已提交的账号信息

注意事项!!!

1.强制推送:强制推送会覆盖远程仓库中的历史记录,因此请确保你了解这个操作的影响,特别是在团队合作的项目中。

2.通知团队成员:如果你在团队合作中进行这些更改,务必通知团队成员,因为他们需要重新同步(git pull –rebase 或重新克隆仓库)以获取更新后的历史记录。

3.备份仓库:在执行这些操作之前,确保备份你的仓库,以防出现意外情况。

推荐使用 git filter-repo 修改已提交的账户姓名和邮箱。

git filter-repo 是一个高效且现代的工具,用于重写 Git 仓库的历史记录。它比旧的 git filter-branch 更快、更易用。

使用 git filter-repo

  1. 安装 git filter-repo

    pacman -S git-filter-repo

    pip install git-filter-repo
  2. 使用 git filter-repo 修改姓名和邮箱

    git filter-repo --commit-callback '
    old_email = b"old-email@example.com"
    new_name = b"new-name"
    new_email = b"new-email@example.com"

    if commit.author_email == b"old_email":
    commit.author_name = b"new_name"
    commit.author_email = b"new_email"
    if commit.committer_email == b"old_email":
    commit.committer_name = b"new_name"
    commit.committer_email = b"new_email" '
    • old_email 替换为你想修改的旧邮箱地址
    • new_name 替换为你希望使用的新用户名
    • new_email 替换为你希望使用的新邮箱地址
  3. 清理仓库(可选)
    git filter-repo 自动清理了大部分历史数据,但你可以运行以下命令进一步清理:

    git reflog expire --expire=now --all && git gc --prune=now --aggressive
  4. 推送更改到远程仓库
    修改历史记录后,你需要强制推送更改到远程仓库

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

使用 git filter-branch

  1. 使用 git filter-branch 更改提交记录中的邮箱

    git filter-branch --env-filter '
    OLD_EMAIL="old-email@example.com"
    CORRECT_NAME="Your Name"
    CORRECT_EMAIL="new-email@example.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 --no-backup
    • old-email@example.com 替换为你想更改的旧邮箱
    • Your Name 替换为你的用户名
    • new-email@example.com 替换为你的新邮箱地址
  2. 推送更改到远程仓库

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