Moving Files / Directories Between Git Repositories Without Loosing History

To Move some Files or Directories from one Git Repository to another one preserving the Git History you can use the "--subdirectory-filter".

With this option, all Commits are parsed to find everyone, matching your selected files.

Make always a copy of your Repositories before starting to Move something, so you wan't loose any Data if something get wrong.

Same procedure was already used by Linus Torvalds the principal force behind the development of the Linux kernel [1] in his "The coolest merge EVER!" [2]

 

Here are the Initial two Repositories:

.
|-- RepositoryA
| `-- ContentA
| `-- contentA.txt
`-- RepositoryB
 `-- ContentB
 `-- contentB.txt

 

We start in RepositoryA and move the Files in the ContentA Directory to RepositoryB

cd RepositoryA
git remote rm origin
git filter-branch --subdirectory-filter ContentA -- --all
# everithing from the directory "ContentA" is now in the root dir of the repositoryA
mkdir ContentA
mv * ContentA

 

 

git add ContentA
git commit

# Do not push anything! Change to your Destinations Repository (RepositoryB)
cd RepositoryB
git remote add Repository-A ../RepositoryA
git pull Repository-A master
# Enter your Merge Commit Message and delete the temporary remote
git remote rm Repository-A

 

Finally you have to create the ContentA Directory again or some similar to clean up your new Repository
mkdir ContentA
mv contentA.txt ContentA

 

.
|-- ContentA
| `-- contentA.txt
`-- ContentB
 `-- contentB.txt

 

[1] http://en.wikipedia.org/wiki/Linus_Torvalds
[2] http://thread.gmane.org/gmane.comp.version-control.git/5126/