更新 Github 仓库历史提交记录的用户信息
本文介绍如何修改 Github 历史提交记录的用户信息,即用户名和邮箱。
最近给其他网友分享我的 Github 仓库时,发现我的提交记录中用户名与我的 Github 账号信息不一致,更严重的是,暴漏了我的真实姓名。
原因应该是我在本地设置了全局的用户名和邮箱,但是没有为每个项目单独设置。
所以,推荐在每个项目开发时,都设置一下本地用户名和邮箱。命令为:
1 2 git config user.name "your-username" git config user.email "[email protected]"本地配置的用户名和邮箱,只会影响当前仓库的提交记录。
接下来就介绍如何修改它,而且是原地更新,不增加额外的提交记录。
1.准备工作:安装修改工具
使用 Github 官方推荐的修改工具 git-filter-repo
1
pip3 install git-filter-repo
在 macos 系统上,可能会提示 error: externally-managed-environment 错误,这个不影响,根使命令提示,增加 --break-system-packages 参数就行。
1
pip3 install git-filter-repo --break-system-packages
2.拉取 Github 仓库
1
2
git clone https://github.com/your-username/your-repo-name.git
cd your-repo-name
注意:把 your-username 和 your-repo-name 替换成你的 Github 用户名和仓库名。
3.修改用户名和邮箱
你可以按需使用不同的更新策略。
本质是使用 --name-callback 参数更新用户名,使用 --email-callback 参数更新邮箱。
参数值使用 Python 代码片段,你可以根据需要编写不同的逻辑,下面是几种常用的更新策略。
3.1 更新所有提交记录
1
2
3
4
5
6
7
8
9
10
11
git filter-repo --force \
--name-callback '
# set all commit names to your-username
name = b"your-username"
return name
' \
--email-callback '
# set all commit emails to [email protected]
email = b"[email protected]"
return email
'
注意:把 your-username 和 [email protected] 替换成你的 Github 用户名和邮箱。
3.2 更新特定用户名的提交记录
1
2
3
4
5
6
7
8
9
10
11
12
13
git filter-repo --force \
--name-callback '
# modify author and committer names
if name == b"OldName":
name = b"NewName"
return name
' \
--email-callback '
# modify author and committer emails
if email == b"[email protected]":
email = b"[email protected]"
return email
'
注意:把 OldName、[email protected] 替换成你的旧用户名和邮箱,NewName 和 [email protected] 同理替换。
4.推送更新
本地更新完成后,需要重新配置远程仓库。然后选择指定分支推送更新即可。
4.1 重新设置远程仓库
1
git remote add origin https://github.com/your-username/your-repo-name.git
注意:把 your-username 和 your-repo-name 替换成你的 Github 用户名和仓库名。
4.2 查看远程仓库分支名
1
git ls-remote --heads origin
输出示例:
1
2
<commit-hash> refs/heads/main
<commit-hash> refs/heads/dev
- refs/heads/main → 默认分支可能是 main
- refs/heads/master → 默认分支可能是 master
4.3 推送更新
根据不同的主分支名,执行推送命令。
1
2
3
git push origin main --force
# 或者
git push origin master --force
