Git修改历史commit的author信息

前言

“嘀嗒嘀嗒”,抬头看向墙上的钟表,此时已是凌晨1点。小明终于把Go语言圣经第二章的笔记写完,保存commit,提交,然后睡觉。
额,等等,不对,小明发现他用的是公司的git账号,git log一看,最新的commit的Author信息里是公司的邮箱地址,尴尬了,难道小明要重新写一遍?“不要啊~”,小明抓狂到。

突然,画面暂停,Git博士从幕后走出,原来是一场电影。Git博士说:“同学们,刚才的案例如果是大家遇到,应该怎样?”,接着说:“不要慌,git rebase帮你解决”

正文

先看一下小明的日志

$git log
commit 34da55544be6ceb1269e24b921275b4a771 (HEAD -> main, origin/main, origin/HEAD)
Author: Company <conpany@company.com>
Date:   Mon Jun 8 01:51:52 2021 +0800

    commit 3

commit 98f419726756cba7923e3c0062bd1231d25
Author: Ming <ming@ming.com>
Date:   Mon Jun 7 20:09:48 2021 +0800

    commit 2

commit 15f0d5882db5dedee737a90e3df98bd395
Author: Company <conpany@company.com>
Date:   Sat May 15 16:34:06 2021 +0800

    commit 1

小明的commit 1commit 3写错了Author信息Company <conpany@company.com>,我们的目标是将这两个commit的作者改成Ming <ming@ming.com> ,让小明早点休息,明天还要去搬砖~

修改上次commit的Author信息

$git commit --commit --author="Ming <ming@ming.com>"

进入一个类似vim编辑器的交互页

commit 3
  
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Author:    ming <ming@ming.com>
# Date:      Mon Jun 7 22:05:18 2021 +0800
#
# On branch master
#
# On branch main
#
# Changes to be committed:
#       new file:   ...
#

保存退出即可

修改以前的commit的Author信息

输入下面的命令,-i参数表示交互方式

git rebase -i HEAD~3

进入一个类似vim编辑器的交互页,将要修改的commit 1开头的pick改成edit

edit acdaa07 commit 1
pick 2f30e03 commit 2
pick 34da555 commit 3

# Rebase b94735d..34da555 onto b94735d (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit

然后保存退出,即:wq,输出下面的下面的信息:

You can amend the commit now, with

    git commit --amend 

Once you are satisfied with your changes, run

    git rebase --continue

接着输入下面的命令来修改提交者信息

$git commit --amend --author="Ming <ming@ming.com>"

最后输入保存命令

$git commit --continue
Successfully rebased and updated refs/heads/master.`

我们再来看下小明的日志

$git log
commit 34da55544be6ceb1269e24b921275b4a771 (HEAD -> main, origin/main, origin/HEAD)
Author: Ming <ming@ming.com>
Date:   Mon Jun 8 01:51:52 2021 +0800

    commit 3

commit 98f419726756cba7923e3c0062bd1231d25
Author: Ming <ming@ming.com>
Date:   Mon Jun 7 20:09:48 2021 +0800

    commit 2

commit 15f0d5882db5dedee737a90e3df98bd395
Author: Ming <ming@ming.com>
Date:   Sat May 15 16:34:06 2021 +0800

    commit 1

大功告成,小明终于可以洗洗睡了,明天今天醒来又是美好的一天~

posted @ 2021-06-08 08:28  Zioyi  阅读(3258)  评论(0编辑  收藏  举报