Extracting subfolders to another repository

David González
2 min readMar 31, 2019

--

At some point during the development of our projects, we have been able to deal with projects where a large number of modules coexisted. And that is something good!

Always developers have tried to have their code the most decoupled so that apart from being testable and scalable, it was easily reusable. But even following these patterns, there is a small step to take further. This step takes into account the reuse of these modules in other projects. We do not know when a specific module of our application can help other colleagues in our company. Or even, the rest of the developers of the world!

In this article we will focus on what steps we need to follow to be able to migrate a subfolder of an existing project and integrate it into a new or existing Git repository. And very important, without losing the commit history.

Be careful! Before you start, create a copy of your project. We do not want to take any risk in case there is a mistake! Instead of making a copy, you can clone your project in another directory and work from there.

In both cases, as a first step, we will remove the link to the remote repository to keep a local copy.

git remote rm origin

Now, we will isolate all the files in the subfolder that you want to migrate.

git filter-branch --subdirectory-filter target-folder -- --all

You will see that only the content of the chosen folder has been left in the root of the repository folder. But we have not finished yet! Now, you have to put again all those files in the folder they came from. This way we will have all the files that we want to migrate exactly where they should be.

mkdir target-folder
mv * target-folder

Next step may vary depending of the situation of your destination repository. If you do not have a remote repository you will have to create one right now.

mkdir destination-folder
cd destination-folder
git init
git remote origin destination-repository-url

On the other hand, if you already have a repository previously created, whether you have previous content or not, clone it.

In both cases, you have just created or cloned it, these are the final steps to complete the migration.

git remote add migration origin-repository-folder
git pull migration master --allow-unrelated-histories
git remote rm migration

The source repository will be practically useless with a history of Git overwritten by all these changes which have occurred. But, as we have worked on a copy you can delete it with any problem.

Maybe you have used tags in your previous repository. All tags are also kept in this new repository, but you may not need them. In this case you can delete them!

git tag -d useless-tag

Now, you can push to your remote repository. Migration completed! 🚀

--

--