GIT: How to move subfolder between repositories

Sometimes you need to move a subdirectory between two GIT repositories with full commit history.

E.g.
repo1/mysubdir --> repo2/mysubdir

Here is how to do it, firstly we download both repositories to our home directory.

user ~$ git clone https://github.com/repo1/
user ~$ git clone https://github.com/repo2/

Secondly we make repo1 “mysubdir” only folder of whole repo. Please note that this will delete all other files from repo in local copy so I really recommend you not to do it on working copy of your repository where you have unstaged files.

user ~$ cd repo1
user ~/repo1 $ git filter-branch --prune-empty --subdirectory-filter mysubdir master
user ~/repo1 $ cd ..
user ~$

Next we will import whole repo (which now contains only selected subdirectory) into a new repository. Please bear in mind that new directory name depends on what is after parameter -P (not how repo1 directory is named)

user ~$ cd repo2
user ~/repo2 $ git subtree add -P mysubdir ~/repo1 HEAD
user ~/repo2 $ git push

And that’s it. You have now moved directory between repositories with full commit history.

Sources: