Skip to content

Instantly share code, notes, and snippets.

@danielpcox
Last active December 16, 2015 01:59
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 danielpcox/5358621 to your computer and use it in GitHub Desktop.
Save danielpcox/5358621 to your computer and use it in GitHub Desktop.
Merge the root of a given branch from repository A into a subdirectory of a given branch in the current repository, preserving yet rewriting the history so that it looks as if A had always been developed inside that subdirectory. It also rewrites the tags to point to the new commits, appending the subdirectory name to the tag names to avoid conf…
#!/usr/bin/env sh
# USAGE: merge-remote.sh <subdirectory-name> <new-local-branch-name> <remote-branch-name> <remote-repository-url>
#
# <new-local-branch> will be created it it does not already exist
SUBDIR_NAME=$1
LOCAL_BRANCH=$2
REMOTE_BRANCH=$3
REMOTE_URL=$4
git remote add $SUBDIR_NAME $REMOTE_URL
git fetch $SUBDIR_NAME
git fetch --tags $SUBDIR_NAME
git checkout -b $SUBDIR_NAME-$REMOTE_BRANCH-tmp $SUBDIR_NAME/$REMOTE_BRANCH
git filter-branch -f --tree-filter "mkdir $SUBDIR_NAME ; mv ./* ./.* $SUBDIR_NAME/ || true" --tag-name-filter "sed 's/.*/&-$SUBDIR_NAME/'"
git branch $LOCAL_BRANCH
git checkout $LOCAL_BRANCH
git merge -m "Merged $SUBDIR_NAME repository into subdirectory" $SUBDIR_NAME-$REMOTE_BRANCH-tmp
#git branch -D $SUBDIR_NAME-$REMOTE_BRANCH-tmp
#git remote rm $SUBDIR_NAME
##the old tag names also need to be manually removed with "git tag -d <tagname>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment