Sometimes, when you work with team, you need to clone a separated code to integrate a plugin/module to your repository. It happens when I work on a CakePHP project and I need a plugin from CakeDC’s repositories. Perhaps, I don’t maintain CakeDC’s plugin. And I don’t care about pull requests and commits of the submodule. Another example, I have a CakePHP Dev environment cloned from this repository. So, I create my own application in app folder as a submodule. So, that’s why I want to share the basic to how to create, delete and update a Git submodule.
Create & Initiate a submodule
To add a submodule, you have to run this command:
git submodule add https://github.com/user/repo.git
Then, this command will create a .gitmodules file and a folder of the submodule you just added in your initial repository. This file will contains submodules:
[submodule "RepoFolder"]
path = RepoFolder
url = https://github.com/user/repo.git
If you want to show diff of your main project, you’ll have to add –module flag like this:
git diff --cached --submodule
To update the sub-module repository, you can enter to the folder and run fetch/pull or you can run this from the main repository git submodule update --remote RepoFolder
Remove a submodule from a repository
First, I will show you how to manually delete the submodule. First step, You need to delete the .gitmodules
from the main repository. Then, you need to stage it by adding it to git git add .gitmodules.
You should then delete the section on .git/config. Then, git rm --cached RepoFolder
. This will remove the folder. Then, run rm -fr .git/modules/RepoFolder
. Finally, commit the changes and you’ll see the submodule folder untracked.
The simplest way to delete the submodule is this:
git submodule deinit RepoFolder
git rm RepoFolder
git commit-m "Removed submodule 🙅♂️"
rm -rf .git/modules/RepoFolder
I hope you like this post. If you want more about git I suggest you to take a look at Pro Git commands you should know 👈