Search code examples
gitgithubcommitrebase

Change author name and email of Git/GitHub repository keeping timestamps for all commits


I have changed my username on GitHub recently, additionally I wanted to hide my real email from the commits and preserve the commit history. Let's assume I don't have any contributors, so all commits are mine. Found a few suggestions to use git filter-branch, but running it I've got a warning that it could corrupt my repository. Are there any alternatives?


Solution

  • So if the original hashes are not required or not referenced anywhere, and only the author name/email needs to be updated, there are two simple steps to do that.

    Be aware that it's not reversible, so make sure to have a backup.

    1. Set new name and email to git configuration:
    git config --global user.name "FIRST_NAME LAST_NAME"
    git config --global user.email "MY_EMAIL@SOME_DOMAIN.com"
    

    Skip --global for repository-specific username/email configuration.

    1. Run this one-liner on the needed branch of the repository:
    git rebase -i --rebase-merges --root --exec 'GIT_COMMITTER_DATE="$(git log -n 1 --format=%aD)" git commit --amend --reset-author --no-edit --date="$(git log -n 1 --format=%aD)"'
    

    The editor will be opened up with the list of all commits and command which will be executed on each commit. Nothing need to be done here, just save and exit. After that the changes will be applied.

    So what it does basically, is running re-base in interactive mode starting from the first commit ever. For each commit it grabs the date of the original commit, sets GIT_COMMITTER_DATE (important for the GitHub) and timestamp (will be shown in git log), resets whomever author of the commit it is, and amends the changes. Then goes to the next commit. That's it, now you just need to force push the changes to update the GitHub repository.

    git push -f
    

    Again, try these steps on the copy of the repository first!