修改GIT历史记录

发布时间 2023-05-29 12:22:16作者: 一块白板

准备工作

GIT:https://git-scm.com/download/win

[可选]Idea: https://www.jetbrains.com/zh-cn/idea/

开始修改

命令行模式

打开命令行,将命令行的路径指向需要修改的项目。输入如下命令:

git rebase -r -i <commitid>^
# commitid 为需要开始修改的提交id

在自动打开的编辑器(VI)中 将 需要修改的部分的 pick 换成 edit或者e,保存文件。

label onto

reset onto
edit a919b87 feat(*): 2023.4.27
pick bf04b11 feat(*): 2023.4.27
pick 8297899 feat(*): 2023.4.27
pick 756874d feat(*): 2023.4.28
pick 85488a3 feat(*): 2023.5.10
pick fa891d8 feat(*): 2023.5.16

# Rebase 4f81358..fa891d8 onto 4f81358 (8 commands)
.git/rebase-merge/git-rebase-todo[+] [unix] (11:10 29/05/2023)  

rebase将在遇到edit的时候自动停止。此时代码会处于该提交历史的状态,此时可以同正常一样进行操作。

编辑完成后 使用

git add . 
GIT_COMMITTER_DATE="2021-05-21T12:09:28" GIT_COMMITTER_NAME="xxx" GIT_COMMITTER_EMAIL="xxxx@163.com" git commit --amend --author "xxx<xxxx@163.com>" --no-edit
git rebase --continue

GIT_AUTHOR_NAME is the human-readable name in the “author” field.

代码的作者名称字段

GIT_AUTHOR_EMAIL is the email for the “author” field.

代码的作者邮箱字段

GIT_AUTHOR_DATE is the timestamp used for the “author” field.

代码的作者时间字段

GIT_COMMITTER_NAME sets the human name for the “committer” field.

代码的提交者名称字段

GIT_COMMITTER_EMAIL is the email address for the “committer” field.

代码的提交者邮箱字段

GIT_COMMITTER_DATE is used for the timestamp in the “committer” field.

代码的提交者提交时间字段

最后使用 ,强行提交

git push -f

Idea模式

打开菜单下的 Git -> Rebase
勾选如下选项:
image
再出来的确认框选择 Rebase Anyway
image
将需要修改的历史的 pick 改为 edit
image
剩余步骤同命令行模式一致,只是将后续的操作转为Idea上操作

已知问题

  • 提交人和作者不一致
    git add 的时候修改 GIT_COMMITTER_NAME GIT_COMMITTER_EMAIL 可以解决
  • Merge branch 'master' of xxxxxxxx 这个提交时间没法修改
    此问题目前无解

其他相关命令


# 设置全局
git config --global user.name "Author Name"
git config --global user.email "Author Email"

# 或者设置本地项目库配置
git config user.name "Author Name"
git config user.email "Author Email"

参考资料

https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History
https://cloud.tencent.com/developer/article/1428060
https://zhuanlan.zhihu.com/p/54375755
https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables