How to Add a Submodule to a Git Repository

Steps to Add a Git Submodule

Adding a submodule to a Git repository can be a bit tricky, especially for those new to Git. This article helps you understand how to easily integrate external repositories as submodules into your project, addressing common issues such as maintaining dependencies and organising your project. Follow these steps:

In the terminal, go to the directory of the repository where you want to add the submodule:

cd /path/to/your/repo

2. Add the Submodule

Use the git submodule add command, followed by the URL of the submodule repository and the path where it should be added:

git submodule add <repository_url> <path>

  • ​<repository_url>: The URL of the repository you want to add as a submodule (e.g., a GitHub repository).
  • ​<path>: The directory where the submodule will reside. If left blank, it will default to the name of the submodule repository.
Example

git submodule add https://github.com/example/submodule-repo.git submodules/submodule-repo
or
git submodule
add https://github.com/example/submodule-repo.git

3. Initialise the Submodule

Once the submodule is added, initialise it to ensure it's set up:

git submodule init

4. Update the Submodule

Fetch the submodule’s contents:

git submodule update

5. Commit the Changes

Commit the changes to include the submodule in your main repository:

git add .gitmodules submodules/submodule-repo
git commit -m
"Added submodule"

6. Cloning a Repository with Submodules

(For Other Collaborators)

If someone else clones your repository, they will need to initialise and update the submodules:

git clone <main_repo_url>
git submodule init
git submodule update
// For all
submodule code fetch
git submodule update -init -remote -recursive
// For specific
submodule code fetch
git submodule update -init -remote submodule_name

Alternatively, they can clone with submodules in one step:

git clone --recurse-submodules <main_repo_url>

By following these steps, you can easily add and manage submodules in your Git repository, ensuring a more organised project structure.

Need more development tips?

Stay tuned to our blog.

Dharmesh Patel 1 نوفمبر, 2024
أرشفة
تسجيل الدخول حتى تترك تعليقاً
Merge Request Update After the Code Review