%% date:: [[2023-05-06]] parent:: [[Git]] %% # [[Subtrees in Git]] A subtree in [[Git]] is a subdirectory or sub-folder within a Git repository that you want to track separately. It's a way to nest a repository inside another. ![[bitbucket-subtrees.png]] [^bitbucket] ## Why would you use it? Simply [[Branching in Git#^1b2f9b|creating and checking out a branch]] would just copy the entire main branch to the new branch, but using a subtree means that only the subfolder is copied over. One concrete use case for this is to post only a subdirectory to a different branch on [[GitHub]], such as to [[Deploying a subfolder to GitHub Pages|deploy a subfolder to GitHub Pages]]. ## Advantages and disadvantages ### Advantages of using a subtree - Subtrees have a simple workflow that don't require users of your repository to do anything different to download the subtree, since cloning the parent repo clones the subtree as well. - Subtrees don't require new metadata files, whereas [[Submodules in Git|submodules]] require a new `.gitmodule` file when used. - All the information/dependencies are available in a single repo. ### Disadvantages of using a subtree - Using subtrees requires using a new merge strategy (`git subtree`). - If you want to contribute upstream, the workflow is a bit trickier. - It can be easy to mix code between your main tree and subtree. [^bitbucket] ## Usage ### Add a subtree ``` git add path/to/subfolder && git commit -m 'Initial commit' ``` ### Push to a subtree ``` git subtree push --prefix path/to/subfolder origin gh-pages ``` where `gh-pages` is the branch of the `origin` repo. ## Related - [[Submodules vs subtrees vs worktrees in Git]] [^bitbucket]: Paolucci, N. Atlassian Bitbucket. Retrieved on May 6th, 2023 from https://www.atlassian.com/git/tutorials/git-subtree