Skip to content

Instantly share code, notes, and snippets.

@StudioLE
Last active September 14, 2021 08:41
Show Gist options
  • Save StudioLE/d0fb1ff5217b32ee901d92287f6b2def to your computer and use it in GitHub Desktop.
Save StudioLE/d0fb1ff5217b32ee901d92287f6b2def to your computer and use it in GitHub Desktop.
Git rewrite tags as commits. Squash everything but preserve tags.
#!/bin/bash
ORIGINAL_BRANCH="main"
NEW_BRANCH="new-history"
START_COMMIT="84eafe059aa3059d2e3db260a2248deae7502c57"
NEW_TAG_PREFIX="v2-"
git checkout -b ${NEW_BRANCH} ${START_COMMIT}
# Loop through every tag on the ORIGINAL_BRANCH
for TAG in $(git tag --merged ${ORIGINAL_BRANCH})
do
echo "----------------------------------------------------------------------------------------------------"
echo "Re-creating ${TAG}"
echo "----------------------------------------------------------------------------------------------------"
# Retrieve all the metadata for the commit
# https://git-scm.com/docs/git-show#Documentation/git-show.txt-emsem
MSG=$(git show -s --pretty=tformat:%s ${TAG})
# https://git-scm.com/docs/git-show#Documentation/git-show.txt-emaiem
DATE=$(git show -s --pretty=tformat:%ai ${TAG})
# https://git-scm.com/docs/git-show#Documentation/git-show.txt-emanem
AUTHOR_NAME=$(git show -s --pretty=tformat:%an ${TAG})
# https://git-scm.com/docs/git-show#Documentation/git-show.txt-emaeem
AUTHOR_EMAIL=$(git show -s --pretty=tformat:%ae ${TAG})
# Create a new commit command using the metadata. Ensure the author and committer are set.
COMMIT="git -c user.name=\"${AUTHOR_NAME}\" -c user.email=\"${AUTHOR_EMAIL}\" commit --allow-empty -m \"${MSG}\" --date \"${DATE}\""
# Remove all files except hidden
rm -r `ls`
# Checkout all files at tag
git checkout ${TAG} -- .
# Stage all files
git add .
# Commit all files
bash -c "${COMMIT}"
# Create tag
git tag "${NEW_TAG_PREFIX}${TAG}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment