一、Change last commit author

创建一个 amend 提交,重写作者

1
2
3
4
# git commit --amend --author="<name> <email>" --no-edit
# 注意这里的邮箱是要带尖括号的 eg.
git commit --amend --author="cai.dog" "<caidog@xxx.com>" --no-edit

然后再强制 Push 即可

1
2
git push --force <repository> <branch>
git push -f origin master

或者更安全的强制推送

1
git push --force-with-lease <repository> <branch>

或者新的分支

1
git push <repository> +<branch>

二、Change more than a commit

git log查看提交 hash,就是 commit-id

1
git log

然后 rebase 到当前要修改位置的上一个 previous-commit-id

1
2
# git rebase -i -p <previous-commit-id>
git rebase -i -p 4d133f673250ed628e58371a8b246d68171fbbf9

然后也会看到有提示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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 <commit> = run command (the rest of the line) using shell
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# . create a merge commit using the original merge commit's
# . message (or the oneline, if no original merge commit was
# . specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#

此时,我们把提交 Pick 出来,直接p进入编辑状态
然后就是一个类似于 VIM 的编辑状态,基本命令如下

1
2
3
4
i: Enter to insert mode
ESC: Exit of the insert mode
:wq: Write and quit
:q: Quit

接下来修改当前提交

1
git commit --amend --author="XXX <xxx@abc.com>" --no-edit

再继续下一个

1
git rebase --continue

再提交

1
git push origin <branch-name>

或者强制提交

1
git push -f origin <branch-name>

二、Gitlab 时 push 不上去的问题

如果是 Gitlab 的服务器,在 Push 的时候可能会有保护的问题

1
Git push error pre-receive hook declined

解决办法

  • 进入 Gitlab 后台,进入当前工程

  • Setting => Repository => Protected Branches

  • 点击展开Expand后,会有一个Protect a branch 的设置

  • 选择好分支的权限组后,再打开Allowed to force push

  • 点击按钮Protect

  • 此时会在下面弹出一个询问,选择UnProtect

然后再客户端重新 push 即可

三、参考

https://dev.to/brayanarrieta/how-to-change-the-git-commit-author-56mg

有人在 github 重新写了一个 sh 脚本,可以直接使用
https://github.com/MichaelCurrin/rewrite-git-author