抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

查看当前用户名和邮箱

1
2
3
$ git config user.name

$ git config user.email

修改全局用户名和邮箱

1
2
3
$ git config --global user.name "username"

$ git config --global user.email "email@example.com"

如果只是设置当前项目的用户名和邮箱,可以去掉全局选项:--global

可以通过全局配置文件修改,打开:C:\Users\用户名\.gitconfig

1
2
3
[user]
name = Author name
email = email@example.com

修改提交记录中的用户名和邮箱

修改单条记录

如果只是修改最近一次 commit 的作者信息

1
git commit --amend --author="NewAuthor <NewEmail@example.com>"

如果需要大批量修改 commit 信息,就需要使用以下脚本执行。

git filter-branch

filter-branch 命令可以用来改写大量的历史提交记录,比如修改用户名称、邮箱、移除文件等等。如果需要修改提交历史中的用户名和邮箱,可以这样操作:

  1. 执行命令,修改变量后执行即可。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    $ git filter-branch --env-filter '

    OLD_EMAIL="old.email@example.com"
    CORRECT_NAME="NewName"
    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
  1. 查看修改是否有错误

    1
    $ git log
  2. 提交新的 commit 信息

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

git-filter-repo

filter-branch 命令已被官方不推荐使用,现在推荐使用 git filter-repo 命令。

配置环境

  • git >= 2.22.0
  • python3 >= 3.5

安装 git-filter-repo

安装 git-filter-repo 有很多种方式,这里使用 scoop 来安装。

安装 scoop

scoop 的安装条件:PowerShell 5 以上(包括 PowerShell Core) 和 .NET Framework 4.5 以上。

打开 Windows PowerShell 执行:

1
Set-ExecutionPolicy RemoteSigned -scope CurrentUser

输入 Y 确认,再执行以下命令:

1
PS Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')

Install scoop

安装 git-filter-repo

安装完成 scoop 后就可以安装 git-filter-repo 了:

1
$ scoop install git-filter-repo

install git-filter-repo

如果现在来执行 git filter-repo 命令会提示 Python3 命令无法识别,打开 Python 安装目录,比如:C:\Program Files\Python\Python38,在当前目录启动命令行执行:mklink python3.exe python.exe,做一个软链接。

现在才可以使用 git-filter-repo 命令来执行修改用户名和邮箱的操作了。

在当前 repo 下执行 CMD 新建文件:

type nul>my-mailmap

修改文件内容,格式:

1
New name <new.email@example.com> <old.email@example.com>

执行修改命令:

1
$ git filter-repo --mailmap my-mailmap --force

添加远程分支:

1
2
$ git remote add origin https://github.com/varm/repo.git
$ git push --set-upstream origin master --force

使用回调函数重写用户名和邮箱

  1. 将所有用户名中包含的 foo 替换成 NewName (注意,不支持中文)

    1
    git filter-repo --name-callback 'return name.replace(b"foo", b"ttys3")'
  2. 将所有 commit 信息的 Email 中包含的 foo@example.com 替换成 my-email@example.com

    1
    git filter-repo --email-callback 'return email.replace(b"foo@example.com", b"my-email@example.com")'

评论