修改Git提交历史中的用户信息

102次阅读
没有评论

修改 Git 提交历史中的用户信息

转载:https://juejin.cn/post/7036174938306248717

在我们日常工作中,通常由于某种原因,需要更新历史提交的 commit 信息。一般会有如下几种场景:

  • 修改当前分支最新 commit 的提交信息
  • 修改当前分支某历史 commit 的提交信息
  • 修改当前分支所有提交的 commit 信息

对于当次提交来说,我们可以显示指定提交者信息。

git commit -m "Initial commit" --author="mn <mn@furzoom.com>"

通过 git commit 命令将暂存区内容添加到本地仓库后,git 会生成相应的 commit id。后续我们就可以针对指定的 commit id 进行操作,比如,回退到某个 commit id,拉取指定 commit id 的代码等。

下面我们针对上面的三种情况进行讲述。

修改上次提交的 commit 信息

git commit --amend --author=" 果冻 <liguodongiot@163.com>"

输入 git commit --amend 之后,进入编辑模式,修改提交信息,然后按 wq 保存退出。

如果不想修改提交信息,则添加--no-edit,如下所示:

git commit --amend --author=" 果冻不吃皮 <mn@furzoom.com>" --no-edit

git commit --amend命令只会修改最后一次 commit 的信息,之前的 commit 需要使用git rebase

修改上几次提交的 commit 信息

git rebase -i说明:
git rebase -i命令可以压缩合并多次提交。
格式:git rebase -i \[startpoint\] \[endpoint\]
其中,-i的意思是 –interactive,即弹出交互式的界面让用户编辑完成合并操作,[startpoint] [endpoint] 则指定了一个编辑区间,如果不指定 [endpoint],则该区间的终点默认是当前分支 HEAD 所指向的 commit(该区间指定的是一个前开后闭的区间)。

首先,我们通过 git rebase -i 选择将哪些提交获得重定位。

例如,合并最近的三次提交:

git rebase -i HEAD~3

或者,合并从当前 head 到 15f745b(commit id)的提交:

git rebase -i 15f745b

然后,在列表中将开头的 pick 修改为 edit,然后重复执行以下命令直到完成:

git commit --amend --author="mn <mn@furzoom.com>"

之后,通过 continue 命令回到正常状态。

git rebase --continue

修改之前某一个特定的 commit 信息

查看 log,找到上一次提交的 commit id

git log

然后,通过 git rebase 到要修改的 commit 之前那个 commit。

git rebase 928fc8a3686bf5fcf4527873e075703a9998c127 --interactive(与上面 `git rebase -i` 类似)

然后,在 vi 中修改 pick 为 edit,wq 保存退出,接着进行内容修改,git addgit commit --amend

修改所有提交的 commit 信息

前提:重置本项目用户的信息

git config user.name ' 果冻 '
git config user.email 'liguodongiot@163.com'

方案一:git rebase

首先回到当前分支第一个 commit。

git rebase -i --root

然后,弹出编辑器,在需要修改的 commit 处,将 picked 改变为 edit,然后 wq,退出 vi。

git commit --amend --reset-author

之后,通过 continue 命令回到正常状态。

git rebase --continue 

查看日志,确定是否修改成功

git log

最后,强制 push 到远程仓库

git push origin master -f

方案二:git filter-branch

使用 git rebase 方式,步骤比较多,可以直接使用 git filter-branch快速方便。

例如,将提交者 liguodongiot@163.com 修改为liguodongiot@foxmail.com

# !/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="liguodongiot@163.com"
CORRECT_NAME=" 吃果冻不吐果冻皮 "
CORRECT_EMAIL="liguodongiot@foxmail.com"

if ["$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL"]

then

    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"

fi

if ["$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL"]

then

    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"

fi

' --tag-name-filter cat -- --branches --tags

总结

修改 commit 提交信息场景 操作命令
最新 commit 的提交信息 git commit --amend
历史 commit 的提交信息 git rebase -i father commitId
其中 father commitId 表示上一个 commitld
第一个 commit 的提交信息 git rebase -i --root

注意:如需将修改信息同步到远端仓库,可使用 git push -f 命令进行强制同步,该操作会覆盖远端分支的提交历史,请自行确认操作风险。

 0
评论(没有评论)
验证码