DEV Community

nabbisen
nabbisen

Posted on • Updated on

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

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

Oldest comments (2)

Collapse
 
pierrex profile image
Pierre-Xavier Rousseau

I haven't tried, but I think there is a problem in the example code:

if [ "$GIT_AUTHOR_NAME" != "<old-username>" ] || [ "$GIT_AUTHOR_EMAIL" != "<old-user@e.mail>" ];
Enter fullscreen mode Exit fullscreen mode

should be:

if [ "$GIT_AUTHOR_NAME" = "<old-username>" ] || [ "$GIT_AUTHOR_EMAIL" = "<old-user@e.mail>" ];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nabbisen profile image
nabbisen

Hello, Pierre,

Thank you for your comments and recommendation.

The condition is up to the situation.
I guess I perhaps had to fix all except the pair "old username" - "old email". (It has else clause.)
Well, actually, I forgot what it was more than a year ago. Ha ha.

When convevting the old set to the new one, you are right.