我已经在Git中进行了一系列的提交,现在我意识到我忘记正确设置我的用户名和用户电子邮件属性(新机器)。我还没有将这些提交推到我的存储库中,所以在我这样做之前如何纠正这些提交(只有主分支上的3个最新提交)?

我一直在看git reset和git commit -C <id>——reset-author,但我不认为我在正确的轨道上。


当前回答

我相信你正在寻找的是git rebase -交互式

它允许你重置到一个特定的提交,然后抛出历史更改添加或分组提交

这里有一个解释https://web.archive.org/web/20100213104931/http://blog.madism.org/index.php/2007/09/09/138-git-awsome-ness-git-rebase-interactive

其他回答

如果你在找剧本,这个对我来说很有用。

从GitHub下载脚本,并将其保存到易于访问的位置。 修改脚本文件的权限以允许它执行: Chmod +x changeauthor.sh 导航到具有错误提交历史记录的存储库 cd路径/ /回购 运行脚本(带或不带标志) ../path/to/changeauthor.sh——old-email kaka.ruto@example.com \ ——新邮箱ruto.kaka@example.com——新名字“卡卡·鲁托”——远程起源

小心,因为这将重写您当前目录存储库中的所有历史!好的是脚本会给你关于你要做什么的警告和信息

点击这里阅读更多 https://www.adamdehaven.com/blog/update-commit-history-author-information-for-git-repository/

我相信你正在寻找的是git rebase -交互式

它允许你重置到一个特定的提交,然后抛出历史更改添加或分组提交

这里有一个解释https://web.archive.org/web/20100213104931/http://blog.madism.org/index.php/2007/09/09/138-git-awsome-ness-git-rebase-interactive

投票最多的答案现在已经过时了。Git在使用Git filter-branch -时显示这个可怕的警告

WARNING: git-filter-branch has a glut of gotchas generating mangled history
         rewrites. Hit Ctrl-C before proceeding to abort, then use an
         alternative filtering tool such as 'git filter-repo'
         (https://github.com/newren/git-filter-repo/) instead.

Filter-repo还不是git的一部分,需要手动安装。

# Requires git v2.22+ and python v3.5+. Check with -
git --version && python3 --version
    
# Install using pip
pip install git-filter-repo    
    

要只替换以前提交中的电子邮件,运行如下命令-

git filter-repo --email-callback '
    return email if email != b"incorrect@email" else b"correct@email"
' 

要替换之前提交中的电子邮件和作者名称,运行如下命令-

git filter-repo --commit-callback '
    if commit.author_email == b"incorrect@email":
        commit.author_email = b"correct@email" 
        commit.author_name = b"Correct Name"
        commit.committer_email = b"correct@email" 
        commit.committer_name = b"Correct Name"
' 

当您在终端中粘贴命令时,请确保有缩进。回调使用python语法,因此缩进很重要。

在文档中阅读更多关于filter-repo回调的信息。

只在最后一次提交时更改作者:

git commit --amend --author 'Author Name <author.name@mail.com>' --no-edit

假设你只想改变最后N次提交的作者:

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

笔记

——no-edit标志确保git commit -amend不会要求额外的确认 当你使用git rebase -i时,你可以手动选择要更改作者的提交,

你编辑的文件看起来是这样的:

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

当与exec结合使用时,交互式rebase方法非常好。您可以针对rebase中的特定提交或所有提交运行任何shell命令。

首先设置git作者设置

git config --global user.name "John Doe"
git config --global user.email johndoe@example.com

然后为给定SHA之后的所有提交重置作者

git rebase -i YOUR_SHA -x "git commit --amend --reset-author -CHEAD"

这将弹出编辑器确认更改。您在这里需要做的就是保存并退出,它将通过每次提交并运行-x标志中指定的命令。

根据下面@Dave的评论,你也可以在保持原始时间戳的同时更改作者:

git rebase -i YOUR_SHA -x "git commit --amend --author 'New Name <new_address@example.com>' -CHEAD"