Git, rewrite previous commit usernames and emails

If you have already pushed some of your commits to the public repository, you do not want to do this, or it would make an alternate version of the master's history that others may have used. "Don't cross the streams... It would be bad..."

That said, if it is only the commits you have made to your local repository, then by all means fix this before you push up to the server. You can use the git filter-branch command with the --commit-filter option, so it only edits commits which match your incorrect info, like this:

git filter-branch --commit-filter '
      if [ "$GIT_AUTHOR_EMAIL" = "wrong_email@wrong_host.local" ];
      then
              GIT_AUTHOR_NAME="Your Name Here (In Lights)";
              GIT_AUTHOR_EMAIL="correct_email@correct_host.com";
              git commit-tree "$@";
      else
              git commit-tree "$@";
      fi' HEAD

After applying Olivier Verdier's answer:

git filter-branch -f --env-filter \
"GIT_AUTHOR_NAME='Newname'; GIT_AUTHOR_EMAIL='newemail'; \
GIT_COMMITTER_NAME='committed-name'; GIT_COMMITTER_EMAIL='committed-email';" HEAD

...to push the changed history on the original repository use:

git push origin +yourbranch

The above command (note the plus) forces rewriting the history on the original repo as well. Use with caution!

Again, WARNING: this will make ALL commits as committed by Newname/newemail! The scenario is where you have a repo with only one author who committed using different identities by mistake and you want to fix it.


See here:

git filter-branch -f --env-filter \
"GIT_AUTHOR_NAME='Newname'; GIT_AUTHOR_EMAIL='newemail'; \
GIT_COMMITTER_NAME='committed-name'; GIT_COMMITTER_EMAIL='committed-email';" HEAD

You can add this alias:

git config --global alias.change-commits '!'"f() { VAR=\$1; OLD=\$2; NEW=\$3; shift 3; git filter-branch --env-filter \"if [[ \\\"\$\`echo \$VAR\`\\\" = '\$OLD' ]]; then export \$VAR='\$NEW'; fi\" \$@; }; f"

To change the author name:

git change-commits GIT_AUTHOR_NAME "old name" "new name"

or the email for only the last 10 commits:

git change-commits GIT_AUTHOR_EMAIL "[email protected]" "[email protected]" HEAD~10..HEAD

Alias:

change-commits="!f() { VAR=$1; OLD=$2; NEW=$3; shift 3; git filter-branch --env-filter \"if [[ \\\"$`echo $VAR`\\\" = '$OLD' ]]; then export $VAR='$NEW'; fi\" \$@; }; f"

Source: https://github.com/brauliobo/gitconfig/blob/master/configs/.gitconfig

Tags:

Git