How to convert a Git repo to a submodule, which is nested in another (parent) Git repo?

Change to the main directory, checkout the master branch, and do the following Git command to create a new submodule for plugin1:

git submodule add (url_to_plugin1_repository) subdirectory1/plugin1sm

Here the “url_to_plugin1_repository” points to your current Git repository for plugin1. A new directory will be created call subdirectory1/plugin1sm, which will track your remote repository. I have given it a different name to distinguish it from the plugin1 directory which is not a submodule. Take note that Git will be cloning the data for the plugin1sm directory from the remote url, rather than just copying from your local. That being said, if you have any uncommited changes in your local plugin1 repository, you should commit and push them before doing the above step.

At this point, doing a git status from the main directory should show something similar to the following:

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#   new file:   .gitmodules
#   new file:   subdirectory1/plugin1sm

Since you are in the main directory, the new submodule shows up as a “file” in the changeset. You can commit this change with the following commands:

$ git add subdirectory1/plugin1sm
$ git commit -m "Created submodule for plugin1"
$ git push origin master

The next question which will probably come to your mind is how do you go about using the new submodule along with your main Git repository. Let’s start by looking into what happens when you work on files inside the plugin1sm directory. When you work inside the plugin1sm directory, Git will track changes and behave as if it doesn’t know about anything outside of that directory. When the time comes to commit and push your changes, you use the following expected commands:

$ cd subdirectory1/plugin1sm
$ git add <yourfile>
$ git commit -m "modified my file"
$ git push

But what about the main repository? Here is where things get a little interesting. Since you modified your plugin1sm submodule, it will show up as a modified “file” in the changeset of the main repository. To continue, you can add the submodule and push it with the following commands:

$ cd ../../
$ git add subdirectory1/plugin1sm
$ git commit -m "updated my submodule"
$ git push origin master

So to summarize, your basic Git workflow within a submodule will be business as usual, and within your main repository, you will need to keep in mind that the entire submodule will appear as a file. Things get more complex than the simple use case we considered here, but hopefully this sets you on the right path.

You can repeat this procedure for the plugin2 and plugin3 directories. And when you have finished creating the submodules, you should be able to delete the original plugin directories.

Leave a Comment