Differences between git submodule and subtree

GitGit SubmodulesGit Subtree

Git Problem Overview


What are the conceptual differences between using git submodule and subtree?

What are the typical scenarios for each?

Git Solutions


Solution 1 - Git

submodule is link;

subtree is copy

Solution 2 - Git

> What if I want the links to always point to the HEAD of the external repo?

You can make a submodule to follow the HEAD of a branch of a submodule remote repo, with:

o git submodule add -b <branch> <repository> [<path>]. (to specify a branch to follow)
o git submodule update --remote which will update the content of the submodule to the latest HEAD from <repository>/<branch>, by default origin/master. Your main project will still track the hashes of the HEAD of the submodule even if --remote is used though.


Plus, as noted by philb in the comments, git subtree is a contrib/, as opposed to git submodule (core command)

Solution 3 - Git

The conceptual difference is:

With git submodules you typically want to separate a large repository into smaller ones. The way of referencing a submodule is maven-style - you are referencing a single commit from the other (submodule) repository. If you need a change within the submodule you have to make a commit/push within the submodule, then reference the new commit in the main repository and then commit/push the changed reference of the main repository. That way you have to have access to both repositories for the complete build.

With git subtree you integrate another repository in yours, including its history. So after integrating it, the size of your repository is probably bigger (so this is no strategy to keep repositories smaller). After the integration there is no connection to the other repository, and you don't need access to it unless you want to get an update. So this strategy is more for code and history reuse - I personally don't use it.

Solution 4 - Git

sub-module
pushing a main repo to a remote doesn't push sub-module's files

sub-tree
pushing a main repo to remote pushes sub-tree's files

Solution 5 - Git

The simplest way to think of subtrees and submodules is that a subtree is a copy of a repository that is pulled into a parent repository while a submodule is a pointer to a specific commit in another repository.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan HView Question on Stackoverflow
Solution 1 - GitFengView Answer on Stackoverflow
Solution 2 - GitVonCView Answer on Stackoverflow
Solution 3 - GitNiklas PView Answer on Stackoverflow
Solution 4 - GitMaciek RekView Answer on Stackoverflow
Solution 5 - GitPervaiz IqbalView Answer on Stackoverflow