How to change the author and committer name and e-mail of multiple commits in Git?

后端 未结 30 3046
野性不改
野性不改 2020-11-21 04:50

I was writing a simple script in the school computer, and committing the changes to Git (in a repo that was in my pendrive, cloned from my computer at home). After several c

30条回答
  •  误落风尘
    2020-11-21 04:52

    We have experienced an issue today where a UTF8 character in an author name was causing trouble on the build server, so we had to rewrite the history to correct this. The steps taken were:

    Step 1: Change your username in git for all future commits, as per instructions here: https://help.github.com/articles/setting-your-username-in-git/

    Step 2: Run the following bash script:

    #!/bin/sh
    
    REPO_URL=ssh://path/to/your.git
    REPO_DIR=rewrite.tmp
    
    # Clone the repository
    git clone ${REPO_URL} ${REPO_DIR}
    
    # Change to the cloned repository
    cd ${REPO_DIR}
    
    # Checkout all the remote branches as local tracking branches
    git branch --list -r origin/* | cut -c10- | xargs -n1 git checkout
    
    # Rewrite the history, use a system that will preseve the eol (or lack of in commit messages) - preferably Linux not OSX
    git filter-branch --env-filter '
    OLD_EMAIL="me@something.com"
    CORRECT_NAME="New Me"
    
    if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
    then
        export GIT_COMMITTER_NAME="$CORRECT_NAME"
    fi
    if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
    then
        export GIT_AUTHOR_NAME="$CORRECT_NAME"
    fi
    ' --tag-name-filter cat -- --branches --tags
    
    # Force push the rewritten branches + tags to the remote
    git push -f
    
    # Remove all knowledge that we did something
    rm -rf ${REPO_DIR}
    
    # Tell your colleagues to `git pull --rebase` on all their local remote tracking branches
    

    Quick overview: Checkout your repository to a temp file, checkout all the remote branches, run the script which will rewrite the history, do a force push of the new state, and tell all your colleagues to do a rebase pull to get the changes.

    We had trouble with running this on OS X because it somehow messed up line endings in commit messages, so we had to re-run it on a Linux machine afterwards.

提交回复
热议问题