Skip to content

Instantly share code, notes, and snippets.

@pdarragh
Created January 26, 2021 22:35
Show Gist options
  • Save pdarragh/e593f3ff0d03103c68b709b59db6f886 to your computer and use it in GitHub Desktop.
Save pdarragh/e593f3ff0d03103c68b709b59db6f886 to your computer and use it in GitHub Desktop.
Move commits from one repository to another without squashing
#!/usr/bin/env sh
# I TAKE NO RESPONSIBILITY FOR YOUR CHOICE TO USE THIS SCRIPT.
# It's probably a better idea to just read the commands and enter
# them by hand one-by-one. But I've used this script and it works
# for me, so here it is.
# Migrates the commits from an old repository to a new one using
# a rebase.
#
# NOTE: FAVORS COMMITS FROM THE OLD REPO WHEN THERE IS CONFLICT.
# If you want to favor the new repo, use "theirs" as the
# STRATEGY (fourth argument).
# NOTE: RUN THIS SCRIPT FROM YOUR NEW REPOSITORY.
OLD_REMOTE="$1"
OLD_BRANCH="${2:-main}"
NEW_BRANCH="${3:-main}"
STRATEGY="${4:-theirs}"
if [ -z "${OLD_REMOTE}" ] || [ -z "${OLD_BRANCH}" ] || [ -z "${NEW_BRANCH}" ]; then
>&2 echo "usage: $0 OLD_REMOTE [OLD_BRANCH=$OLD_BRANCH] [NEW_BRANCH=$NEW_BRANCH] [STRATEGY=$STRATEGY]"
>&2 echo ""
>&2 echo "Example invocation:"
>&2 echo " $0 [email protected]:username/repository.git master main"
>&2 echo "This will rebase the commits from the master branch of the username/repository"
>&2 echo "repository on top of the main branch of the current repository."
>&2 echo ""
>&2 echo "Call this script from your new repository."
>&2 echo ""
>&2 echo "Values given:"
>&2 echo " OLD_REMOTE: ${OLD_REMOTE}"
>&2 echo " OLD_BRANCH: ${OLD_BRANCH}"
>&2 echo " NEW_BRANCH: ${NEW_BRANCH}"
>&2 echo " STRATEGY: ${STRATEGY}"
exit 1
fi
git remote add oldrepo "${OLD_REMOTE}"
git remote update
git checkout oldrepo/"${OLD_BRANCH}"
git switch -c oldrepo-branch
git pull --rebase -s recursive -X "${STRATEGY}" origin "${NEW_BRANCH}"
git checkout "${NEW_BRANCH}"
git merge --ff-only oldrepo-branch
git remote remove oldrepo
git branch -d oldrepo-branch
echo ""
echo "THE MIGRATION IS COMPLETE, BUT UNPUSHED."
echo "To push the updated content, do:"
echo " \$ git push origin ${NEW_BRANCH}"
echo "To abort the migration and delete all unpushed commits, do:"
echo " \$ git reset --hard origin"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment