Content Entry

Moving a Subdirectory to a Submodule in Git

Sometimes when you work on a project long enough, you find that for one reason or the other, parts of the project should be in a separate repository. Either the subdir contains reusable code, to be used on another project, or - as it was in our case today - some part of the project, was needed on many servers, and the rest only on one. We decided to create a separate module to ensure that we did not clone the entire projects for these servers.

There are two steps to this procedure. 1. Get the subdir - with the complete git history into a new repo, and 2. get the new repo in to the old project as a submodule.

This is how you move "Application/scripts/shell" from OldProject into its own repo called NewProject. And then link it as a submodule at the same location it were before.

Subdir to another repo

git clone --no-hardlinks OldProject NewProject
cd NewProject
git filter-branch --subdirectory-filter Application/scripts/shell HEAD
git reset --hard
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --aggressive --prune=now
Next you need to set the remote (in our case origin) to the new repo's remote.

Create submodule

Back in the old project, remove the part you have extracted, and commit. Then run the following commands.

git submodule add Application/scripts/shell
-- commit --
git submodule init
git submodule update
-- commit again --

You should now have you former subdirectory as a separate repository, at the same location.


comments loading