如何更改一系列提交的作者?


当前回答

对于重置当前用户和当前时间戳的所有提交(包括首次提交):

git rebase --root --exec "git commit --amend --no-edit --date 'now' --reset-author"

其他回答

注意:这个答案会改变SHA1,所以在已经推送的分支上使用它时要小心。如果你只想修复一个名字的拼写或更新一封旧邮件,Git可以让你不用使用.mailmap重写历史。

使用回扣

首先,如果您还没有这样做,您可能需要在git-config中修复您的名称:

git config --global user.name "New Author Name"
git config --global user.email "<email@address.example>"

这是可选的,但它也将确保重置提交者名称,假设这是您所需要的。

要使用rebase重写一系列提交的元数据,请执行

git rebase -r <some commit before all of your bad commits> \
    --exec 'git commit --amend --no-edit --reset-author'

--exec将在每次提交被重写后运行gitcommit步骤(就像您运行gitcommit&&gitrebase一样——重复继续)。

如果您还想更改第一次提交(也称为“root”提交),则必须在rebase调用中添加--root。

这将把提交人和作者都更改为user.name/user.email配置。如果不想更改该配置,可以使用--author“New author Name”<email@address.example>“而不是--reset-author。请注意,这样做不会更新提交者,只更新作者。

单次提交

如果您只想更改最近的提交,则无需重新设置基准。只需修改承诺:

 git commit --amend --no-edit --reset-author

整个项目历史

git rebase -r --root --exec "git commit --amend --no-edit --reset-author"

对于较旧的Git客户端(2020年7月之前)

-r、 --您可能不存在重基合并。作为替换,可以使用-p。请注意,-p存在严重问题,现已弃用。

更改最后N次提交的作者的单个命令:

git rebase -i HEAD~N -x "git commit --amend --author 'Author Name <author.name@mail.example>' --no-edit"

笔记

用引用替换HEAD~N,直到您要重写提交的地方。这可以是哈希、HEAD~4、分支名称。。。--no edit标志确保gitcommit--modify不会要求额外的确认当您使用gitrebase-i时,您可以手动选择要更改作者的提交位置,

您编辑的文件将如下所示:

pick 897fe9e simplify code a little
exec git commit --amend --author 'Author Name <author.name@mail.example>' --no-edit
pick abb60f9 add new feature
exec git commit --amend --author 'Author Name <author.name@mail.example>' --no-edit
pick dc18f70 bugfix
exec git commit --amend --author 'Author Name <author.name@mail.example>' --no-edit

然后,您仍然可以修改一些行,以查看要更改作者的位置。这为您在自动化和控制之间提供了一个很好的中间地带:您可以看到将要运行的步骤,一旦您保存了所有内容,将立即应用。

请注意,如果您已经使用git-configuser.name<your_name>和git-config user.email<your_email>修复了作者信息,那么也可以使用以下命令:

git rebase -i HEAD~N -x "git commit --amend --reset-author --no-edit"

如果您要修复的提交是最新的,并且只有几个,您可以使用git reset和git stash的组合,在配置正确的名称和电子邮件后再次提交。

顺序如下(对于2个错误的提交,没有挂起的更改):

git config user.name <good name>
git config user.email <good email>
git reset HEAD^
git stash
git reset HEAD^
git commit -a
git stash pop
git commit -a

我已经尝试了上面的脚本,但它不适合我,这解决了我的问题:

使用Git的“filter branch”命令。它允许您使用脚本批量处理(可能大量)提交。您可以在存储库中运行以下示例脚本(填写新旧电子邮件和名称的真实值):

git filter-branch --env-filter '
WRONG_EMAIL="wrong@example.com"
NEW_NAME="New Name Value"
NEW_EMAIL="correct@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$WRONG_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$NEW_NAME"
    export GIT_COMMITTER_EMAIL="$NEW_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$WRONG_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$NEW_NAME"
    export GIT_AUTHOR_EMAIL="$NEW_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

在此处查看更多详细信息

对于重置当前用户和当前时间戳的所有提交(包括首次提交):

git rebase --root --exec "git commit --amend --no-edit --date 'now' --reset-author"