Convert a Git folder to a submodule retrospectively? Ask Question

Convert a Git folder to a submodule retrospectively? Ask Question

Quite often it is the case that you're writing a project of some kind, and after a while it becomes clear that some component of the project is actually useful as a standalone component (a library, perhaps). If you've had that idea from early on, then there's a fair chance that most of that code is in its own folder.

Is there a way to convert one of the sub directories in a Git project to a submodule?

Ideally this would happen such that all of the code in that directory is removed from the parent project, and the submodule project is added in its place, with all the appropriate history, and such that all the parent project commits point to the correct submodule commits.

ベストアンサー1

To isolate a subdirectory into its own repository, use filter-branch on a clone of the original repository:

git clone <your_project> <your_submodule>
cd <your_submodule>
git filter-branch --subdirectory-filter 'path/to/your/submodule' --prune-empty -- --all

It's then nothing more than deleting your original directory and adding the submodule to your parent project.

おすすめ記事