Open In App

Git Subtree vs. Git Submodule

Git Subtree and Git Submodule are both mechanisms in Git that allow you to incorporate external repositories into your own repository. They provide a way to manage dependencies and include code from other projects while keeping your repository organized and maintainable.

Git Subtree

git remote add -f <remote-name> <repository-url>
git subtree add --prefix=<prefix> <remote-name> <branch> --squash
git subtree push --prefix=<prefix> <remote-name> <branch>
git subtree pull --prefix=<prefix> <remote-name> <branch> --squash

Git Submodule

git submodule add <repository-url> <directory>
git submodule init
git submodule update
git pull origin master

Examples

Let’s say you have a project called “MainProject” and you want to include another project called “SubProject” using both Git Subtree and Git Submodule.

Git Subtree:

git remote add -f subproject-repo https://github.com/example/subproject.git
git subtree add --prefix=subproject subproject-repo master --squash

Git Submodule:

git submodule add https://github.com/example/subproject.git subproject
git submodule init
git submodule update

Shortcomings of git submodules

Shortcomings of git subtrees

FAQs

What’s the main difference between Git Subtree and Git Submodule?

The main difference is in how they incorporate external repositories. Git Subtree embeds the external repository’s code into your own repository, while Git Submodule maintains a separate reference to the external repository.



When should I use Git Subtree over Git Submodule?

Git Subtree is preferred when you want to integrate external code into your repository and treat it as part of your project. It’s useful for cases where you need to make changes to the external code as part of your project’s development.

Can I track changes in the external repository with Git Submodule?

Yes, you can track changes in the external repository by navigating to the submodule directory and pulling changes from the submodule’s repository.

Is it possible to push changes directly to the external repository with Git Submodule?

No, Git Submodule only maintains a reference to the external repository and does not directly push changes to it. You need to navigate to the submodule directory and push changes from there.

Git Subtree and Git Submodule are both valuable tools for managing dependencies and integrating external repositories into your projects. Understanding their differences and use cases can help you make informed decisions when incorporating external code into your Git repositories. Choose the approach that best fits your project’s requirements and workflow.

Article Tags :