Git: Rewrite history on user.name or user.email

nabbisen - May 17 '21 - - Dev Community

Summary

I rewrote the history of one of my Git repositories for security reason last year.
This post is about how I did, referring to the official documentation.
Besides, if it had been a public repository shared with or used by several people, I should have considered more about how to do, especially in communication.

Description

The primary command is below. Well, <*-username> and <*-user@e.mail> are due to environment.

# bash
git filter-branch --commit-filter '
        if [ "$GIT_AUTHOR_NAME" != "<old-username>" ] || [ "$GIT_AUTHOR_EMAIL" != "<old-user@e.mail>" ];
        then
                GIT_AUTHOR_NAME="<new-username>";
                GIT_AUTHOR_EMAIL="<new-user@e.mail>";
                git commit-tree "$@";
        else
                git commit-tree "$@";
        fi' HEAD
Enter fullscreen mode Exit fullscreen mode

It is Git's filter-branch action, a module to "rewrite branches", with --commit-filter <command> filter "for performing the commit", targeting HEAD.
It detects history lines whose username or email isn't valid and rewrites them. Well, of course, you can change the if condition and so on in it.

Then I pushed the rewritten history to hosting service (which was Gitea) I used.

$ git push --force origin main
Enter fullscreen mode Exit fullscreen mode

Here, --force or -f option is necessary for the original lines not to be duplicated. Besides, If they were duplicated unfortunately, you might have to run git reset --hard HEAD^ and then git push --force origin HEAD in order to delete all of the duplicated by restoring the previous commit.

Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .