User Tools

Site Tools


git:git-submodules

Back to git main page

If you clone a git repo inside you git, the best way to handle it is to use modules (sub modules).

Create a submodule

To define a submodule you can use :

git submodule add <git URL> <path>

Where git URL is the URL of the git repo and path is where this git repo is stored in the main git.

For example we are working in the git repo submodules_main and we would like to use an external git at URL https://gitlab.com/bnzr/python_control_coppeliasim.git

mkdir external
git clone https://gitlab.com/bnzr/python_control_coppeliasim.git 
git submodule add https://gitlab.com/bnzr/python_control_coppeliasim.git external/python_control_coppeliasim/

List all submodules

We can list the submodules with :

git submodule foreach --quiet 'echo $name'

Information on submodules can be found in .gitmodules and .git/config of the main project git

Content changes in submodules

If we add the changes, commit and push , the content of submodules will not been added in the main project git, but information on how to retrieve it will be stored. In our example we push the changes :

git add --all
git commit -m "add python_control_coppeliasim external git repo"
git push

Clone git repo with submodules

In another computer we can simply clone the main project repo and we will see that there is nothing in the submodule. The content of the submodules can be pulled by

git clone <git URL> 
cd <git repo main folder>
git submodule update --init

If we know when cloning the main project git that there are submodules we can pull them at the start with –recursive keyword:

git clone <git URL> --recursive

if after pulling the main repo, some new submodules are created and if they are empty, their content can be retrieved with :

git submodule foreach git restore --staged .
git submodule foreach git restore .

Working with a particular submodule (not all)

If the main git repo contains many submodules, it can be interesting to work only on one particular submodule. For example, if after cloning the main git repo the submodule contains nothing, it can be cloned independently of the others submodules. Suppose the path to submodule (from main repo path) is /path/to/mysubmodule, to clone it type :

git submodule init /path/to/mysubmodule
git submodule update -- /path/to/mysubmodule

If the submodule is not in the correct branch, these commands can be used to list the branches and set to the correct one (ex master)

git -C /path/to/mysubmodule branch
git -C /path/to/mysubmodule checkout master

In general a git command on submodule can be acheived from main git repo by :

git -C /path/to/mysubmodule command
git/git-submodules.txt · Last modified: 2024/12/12 08:44 by admin