Skip to content

Instantly share code, notes, and snippets.

@kmilligan
Created January 28, 2013 18:24
Show Gist options
  • Save kmilligan/4657831 to your computer and use it in GitHub Desktop.
Save kmilligan/4657831 to your computer and use it in GitHub Desktop.
Getting contents from a subdirectory of repo A into a different subdirectory of repo B while maintaining history
First, make repoA contain only the files from the subdirectory you care about. To do this, we're going to first create a new working branch, and then use the filter-branch function of git.
cd ~/repoA
git branch -b informative_branch_name
git filter-branch --subdirectory-filter branch/you/want/with/trailing/slash/ -- --all
If you ls, you'll see that the repo contains only the files from the desired subdirectory. It would be a poor decision to push at this time.
Next, visit repoB, and add repoA as a remote. After that, check out the branch you just created (informative_branch_name)
cd ~/repoB
git remote add -f repoA_informative_name /home/username/repoA
git checkout -b repoA_informative_branch_name repoA_informative_name/informative_branch_name
If you check out repoB right now, you'll see that it only contains the files you're caring about - it should be identical to repoA.
Next, a bit of magic. We need to tell git to recreate these files in our desired destination directory.
git filter-branch --index-filter 'git ls-files -s | sed "s-\t\"*-&destination/dir/with/trailing/slash/-" | git update-index --index-info' HEAD
If you look at repoB, you'll see that it now contains all the files you saw last time, but also the directory structure you desire. At this point, you need to clean up everything except that new directory structure. You'll want to rm all files in the base directory (except for your new directories). After removing them, commit.
Finally, you need to merge your new branch into a working branch of repoB.
git checkout repoBs_working_branch
git merge repoA_informative_branch_name
git push
At this point, your files from repoA will exist in your desired directory of repoB, complete with their whole history.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment