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


当前回答

如果您想(轻松)更改当前分支的作者,我会使用类似的方法:

# update author for everything since origin/master
git rebase \
  -i origin/master \
  --exec 'git commit --amend --no-edit --author="Author Name <author.name@email.co.uk>"'

其他回答

我发现所提供的版本非常激进,特别是如果你从其他开发人员那里提交补丁,这将从本质上窃取他们的代码。

下面的版本确实适用于所有分支机构,并分别更改作者和发件人以防止这种情况发生。

感谢leif81的所有选择。

#!/bin/bash

git filter-branch --env-filter '
if [ "$GIT_AUTHOR_NAME" = "<old author>" ];
then
    GIT_AUTHOR_NAME="<new author>";
    GIT_AUTHOR_EMAIL="<youmail@somehost.ext>";
fi
if [ "$GIT_COMMITTER_NAME" = "<old committer>" ];
then
    GIT_COMMITTER_NAME="<new commiter>";
    GIT_COMMITTER_EMAIL="<youmail@somehost.ext>";
fi
' -- --all

对于单个提交:

git commit --amend --author="Author Name <email@address.example>"

(摘自阿斯梅勒的回答)

注意:这个答案会改变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存在严重问题,现已弃用。

如果只有前几次提交的作者不好,您可以使用exec命令和--modify commit在git rebase-i内部执行此操作,如下所示:

git rebase -i HEAD~6 # as required

它为您提供了可编辑的提交列表:

pick abcd Someone else's commit
pick defg my bad commit 1
pick 1234 my bad commit 2

然后添加exec--author=“…”在所有作者不好的行之后:

pick abcd Someone else's commit
pick defg my bad commit 1
exec git commit --amend --author="New Author Name <email@address.example>" -C HEAD
pick 1234 my bad commit 2
exec git commit --amend --author="New Author Name <email@address.example>" -C HEAD

保存并退出编辑器(运行)。

这个解决方案可能比其他解决方案键入的时间更长,但它是高度可控的——我确切地知道它命中了什么提交。

感谢@asmeurer的灵感。

对于windows下的用户,也可以使用git火箭过滤器工具。

根据文档:

更改提交作者姓名和电子邮件:

git-rocket-filter --branch TestBranch --commit-filter '
    if (commit.AuthorName.Contains("Jim")) {   
        commit.AuthorName = "Paul"; 
        commit.AuthorEmail = "paul@company.com"; 
    }