Skip to content

Instantly share code, notes, and snippets.

@emmahsax
Last active November 11, 2020 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmahsax/160f6208b86d1c1746aa8d1ff8d02c3f to your computer and use it in GitHub Desktop.
Save emmahsax/160f6208b86d1c1746aa8d1ff8d02c3f to your computer and use it in GitHub Desktop.
A few files I've used in the past to fix Git history

Fixing Git History

There are two files that I tend to use to fix up some screwed up git history. None of these files should be used on huge repositories where a lot of people have forks and clones. Running any of these files completely rewrites history and will change the git SHA of all of the later commits.

I've used this first file when I've accidentally committed a bunch of past commits with the wrong email (think work vs. personal emails). To use it:

  1. Make a backup branch: git branch default_branch_backup
  2. Make sure you're back on the default branch: git checkout default_branch
  3. Run the script: email_switch.sh
  4. Wait patiently...
  5. Check there's no more bad emails there: echo $(git log) | grep old.email@old.com
  6. FORCE push to default branch: git push -f

Here's the script email_switch.sh:

#!/bin/sh

git filter-branch -f --env-filter '
OLD_EMAIL="old.email@old.com"
CORRECT_EMAIL="new.email@new.com"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

The second file has been used to correct the author/committer dates. I once accidentally did a bunch of correct rewriting of my history, except for one part: GitHub said that all of my commits happened the same day, even though right below the mesasge, it then properly showed each commit's date/time. So, I used the following script to change the committer date to match the author date. This helps to explain the difference between the two: https://alexpeattie.com/blog/working-with-dates-in-git. In order for me to find which date of the two had to be reset, I used the Octokit client to look up a commit, and then figure out which date was incorrect. To use this script:

  1. Make a backup branch: git branch default_branch_backup
  2. Make sure you're back on the default branch: git checkout default_branch
  3. Run the script: reset_committer_date_to_authored_date.sh
  4. Wait patiently...
  5. Cross your fingers that it worked 🤞🏼
  6. FORCE push to default branch: git push -f

Here's the script reset_committer_date_to_authored_date.sh:

#!/bin/sh

git filter-branch -f --env-filter '
export GIT_COMMITTER_DATE=$GIT_AUTHOR_DATE
' --tag-name-filter cat -- --branches --tags
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment