Skip to content

Instantly share code, notes, and snippets.

@pulimento
Last active February 19, 2024 11:58
Show Gist options
  • Save pulimento/879743ef696ed32b314600b9d0bacd1d to your computer and use it in GitHub Desktop.
Save pulimento/879743ef696ed32b314600b9d0bacd1d to your computer and use it in GitHub Desktop.
Rewrite your Git history to change the author's email. Read the inline description first!
#!/bin/zsh
# ==============================================================================
# Script Name: github-email-history.zsh
#
# Description: Script to rewrite your Git history to change the author email for commits with the old email.
# Please note that your remotes will be removed, and you will need to add them back manually.
# First of all, it's recommended to configure your Git user.email to the new email, at least on the working repo.
#
# Usage: script-name.zsh <folder-path> [--force]
#
# Options:
# <folder-path>: The path to the folder containing the Git repository. Mandatory. First parameter
# --force: Optional. Use this option to force the rewrite of the Git history.
#
# ==============================================================================
# Folder path from the first argument
FOLDER_PATH="$1"
# Force it!
if [[ "$2" == "--force" ]]; then
echo "Using --force"
FORCE="--force"
else
FORCE=""
fi
# Define old and new email addresses
OLD_EMAIL="my_old_mail@mail.com"
NEW_EMAIL="my_shiny_new_mail@mail.com"
# Check if the folder path is provided
if [[ -z "$FOLDER_PATH" ]]; then
echo "Error: No folder path provided."
exit 1
fi
# Check if the folder exists
if [[ ! -d "$FOLDER_PATH" ]]; then
echo "Error: The folder path provided does not exist."
exit 1
fi
# Change to the given directory
cd "$FOLDER_PATH" || exit
# Verify if the directory is a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo "Error: The directory is not a git repository."
exit 1
fi
# Check if git-filter-repo is installed
if ! command -v git-filter-repo &> /dev/null
then
echo "Warning! git-filter-repo not installed!. How to install: https://github.com/newren/git-filter-repo/blob/main/INSTALL.md"
exit 1
fi
# Show current remotes
echo "Current Git remotes for repo":
git remote -v
### REAL ACTIONS
# Rewrite Git history to change the author email for commits with the old email
echo "Rewriting Git history for commits with email $OLD_EMAIL to use $NEW_EMAIL..."
git filter-repo --mailmap <(echo "<$NEW_EMAIL> <$OLD_EMAIL>") $FORCE
echo "Git history rewrite complete. Please note that git filter-repo removed your remotes, and this is a 'feature' of the tool. You can add them back with the following command:"
echo "git remote add origin <remote-url>"
# Reminder about pushing changes
echo "Don't forget to push your changes with '--force' to apply the history rewrite remotely."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment