批量修改git commit的作者信息

自己本地环境全局使用的是公司的邮箱, 另外私人项目使用个人邮箱. 但是自己经常忘了设置当前repo的作者, 所以私人项目的代码提交上去后发现, github并不会认为是我提交的修改. 因此, 想要批量修改commit里面的邮箱.

以下代码可以修改所有commit的Author邮箱

git filter-branch --env-filter 'export GIT_AUTHOR_EMAIL=new_author_email' --

除了GIT_AUTHOR_EMAIL, 还有GIT_AUTHOR_NAME, GIT_COMMITTER_EMAIL, GIT_COMMITTER_NAME等参数可以修改.

Committer和Author的区别?

来自Git文档

You may be wondering what the difference is between author and committer. The author is the person who originally wrote the patch, whereas the committer is the person who last applied the patch. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer.

Author是最初写这个commit的人, 而committer是提交这个commit的人. 对于私人项目来说, author和committer都是你自己. 但是如果是多人合作项目, 有一个人提交了PR到你的项目中, 最终是你进行的commit, 那么author和committer就会不一样.

设置本地用户信息

别忘了把本地的用户信息改对:

git config user.name "xxx"
git config user.email "xxx@xxx.com"`

想查看是否生效, 可以

git config -l
// OR
git config -e

高端技

自己定义git alias. 方法:

  1. git commit -e, 打开了文件.git/config
  2. 编辑文件, 加入如下这段
[alias]
        # git change-commits GIT_COMMITTER_NAME "old name" "new name"
    change-commits = "!f() { VAR=$1; OLD=$2; NEW=$3; shift 3; git filter-branch --env-filter \"if [[ \\\"$`echo $VAR`\\\" = '$OLD' ]]; then export $VAR='$NEW'; fi\" $@; }; f "

然后保存.

  1. `git change-commits GIT_AUTHOR_EMAIL “old_email” “new_email”

change-commits失败?

运行git change-commits后报错:

Cannot create a new backup.
A previous backup already exists in refs/original/
Force overwriting the backup with -f

这是因为在你运行完filter-branch指令后, git帮你保存了旧的代码库在.git/refs/original/…, 要么删了这个文件夹, 要么直接加个-f强制执行即可.

参考

  1. Difference between author and committer in Git?
  2. Git, rewrite previous commit usernames and emails
  3. Purging file from Git repo failed, unable to create new backup
    原文作者:柳正来
    原文地址: https://www.jianshu.com/p/cdef3c7b2e3a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞