This tutorial will guide you on how to manage large projects or include external libraries into your project using Git submodules and subtrees. You will learn the differences between submodules and subtrees, and how to use each effectively in your project.
By the end of this tutorial, you will be able to:
- Understand the concept of Git Submodules and Git Subtrees
- Create, update and delete Submodules and Subtrees
- Resolve common issues that arise when using Submodules and Subtrees
Prerequisites:
- Basic knowledge of Git
- Git installed on your local system
Git Submodules allows you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate.
You can add a submodule to your repository using the git submodule add
command followed by the URL of the repository. This will create a new file called .gitmodules
which maps the project URL to your local subdirectory.
git submodule add https://github.com/username/repo.git
When you clone a repository which contains submodules, you need to initialize these submodules using the git submodule init
and then run git submodule update
.
git clone https://github.com/username/repo.git
cd repo
git submodule init
git submodule update
Subtrees allow you to nest one repository inside another as a sub-directory and yet retains the ability to split the section back out into its own repository later.
You can add a subtree to your repository using the git subtree add
command.
git subtree add --prefix=subfolder_name https://github.com/username/repo.git master --squash
Here's an example of creating a new submodule, initializing it and updating it.
# Add the submodule
git submodule add https://github.com/username/repo.git
# Initialize the submodule
git submodule init
# Update the submodule
git submodule update
Here's an example of adding a new subtree to your repository.
# Add the subtree
git subtree add --prefix=subfolder_name https://github.com/username/repo.git master --squash
We've covered how to manage large projects or include external libraries into your project using Git submodules and subtrees. We've learned how to add, initialize, and update submodules as well as how to add subtrees.
For further learning, you can look into:
- Resolving conflicts in submodules and subtrees
- The use of git submodule status
and git submodule summary
Solutions:
bash
git init
git submodule add https://github.com/username/repo.git
bash
git clone https://github.com/username/repo.git
cd repo
git submodule init
git submodule update
bash
git init
git subtree add --prefix=subfolder_name https://github.com/username/repo.git master --squash
Keep practicing and exploring more commands related to git submodules and subtrees. Happy Coding!