Skip to content

Instantly share code, notes, and snippets.

@greyltc
Last active January 18, 2022 13:41
Show Gist options
  • Save greyltc/a49460673f8b9d7a692298d3a131ceb5 to your computer and use it in GitHub Desktop.
Save greyltc/a49460673f8b9d7a692298d3a131ceb5 to your computer and use it in GitHub Desktop.
Changing Git History Author Info

Changing the Git history of your repository using a script[1]

We've created a script that will change any commits that previously had the old email address in its author or committer fields to use the correct name and email address.

Before running this script, you'll need:

  • The old email address that appears in the author/committer fields that you want to change
  • The correct name and email address that you would like such commits to be attributed to
  1. Open a terminal.
  2. Create a fresh, mirror clone of your repository:
    git clone --mirror git@github.com:account/repo.git
    cd repo.git
    
  3. Copy and paste the script, replacing the following variables based on the information you gathered:
    • OLD_EMAIL
    • CORRECT_NAME
    • CORRECT_EMAIL
    #!/bin/sh
    
    FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch --env-filter '
    
    OLD_EMAIL="your-old-email@example.com"
    CORRECT_NAME="Your Correct Name"
    CORRECT_EMAIL="your-correct-email@example.com"
    
    if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
    then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
    fi
    if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
    then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
    fi
    ' --tag-name-filter cat -- --branches --tags
    
  4. Press Enter to run the script.
  5. Delete the duplicate backup history:
    git for-each-ref refs/original --format='delete %(refname) %(objectname)' | git update-ref --stdin
    rm -rf refs/original
    
  6. Collect and discard garbage:
    git reflog expire --expire=now --expire-unreachable=now --all && git gc --prune=now --aggressive
    
  7. Review the corrected history for errors:
    git log --pretty=format:"[%h] %cd - Committer: %cn (%ce), Author: %an (%ae)"
    
    and/or
    git shortlog -sne --all
    
  8. Push the corrected history (note that you might need to unprotect the branch in the guithub branch UI for this to work):
    git push --force
    
  9. Clean up the temporary clone:
    cd ..
    rm -rf repo.git
    

[1]: Modified from the origional which can be seen here: https://web.archive.org/web/20200505044805/https://help.github.com/en/github/using-git/changing-author-info

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment