DEV Community

Arthur
Arthur

Posted on

Git Subtree in 1 minute

"Git subtree" are often described like a better Git Sub-module.

Git subtree gives the possibility to nest one repository into another repository. It's very useful to manage dependencies in your project.

Pro:

  • Modifying content of the module without having another repository.
  • Keep your metadata files clean.
  • Users don't need to learn specific command to modify modules and files.
  • After initializing the subtree, all the code is available in the main tree and subtree.
  • Can create easier workflow.

Cons:

  • Upstream flow is more difficult to modify.
  • Need to use git subtree instead of git merge.
  • Potential mistakes while committing and mixing super and sub into commit.
  • listing multiples subtree is complicated

Creating a subtree

To add a subtree you need a repository with at least 1 commit(initial commit).

Then you can add your subtree like this.

git subtree add --prefix subtreeDirectory https://github.com/arthurlch/mytree.git master --squash

Enter fullscreen mode Exit fullscreen mode

Here we clone this repo --> https://github.com/arthurlch/mytree.git master branch in subtreeDirectory.

Pull new commits to the subtree repository

Use pull instead of add.

Example:

git subtree pull --prefix subtreeDirectory https://github.com/arthurlch/mytree.git master 
Enter fullscreen mode Exit fullscreen mode

UPDATE

You can update the subtree remote repo.

git subtree push --prefix subtreeDirectory https://github.com/arthurlch/mytree.git master
Enter fullscreen mode Exit fullscreen mode

Note: The commit will be stored in the host repository and with it logs.

Conclusion

Subtree > Submodule

Feel free to @ me on Twitter with your opinion & feedback about my article; Constructive feedback is always welcome.

Oldest comments (0)