'How to use git subtree to add local repo?

Say I have a dir that is already a git repo "sub", now I want it to be a subtree of my newly created super directory "sup".

I've searched the document, but all the tutorials are about adding a remote repo or split from the existing commits. How can I add the existed git repo to the main git repo?

Using git subtree add --prefix=sub sub would give the warning sub already exists.



Solution 1:[1]

There are two ways to do this, depending on what you expect.

  1. Add sub repo as a submodule. The repos stay independent
  2. Add sub repo as a subtree of this subrepo. Its histories become merged

For 1, you want to use git submodule. Specifically,

In your sup directory (already initialized with git init) you run:

git submodule add location-of-sub

it will clone the sub repo into the sup repo. You can then remove the sub repo if it is located somewhere else.

Note that submodules still act as different repos than the top repo.

See the documentation for submodules:

https://git-scm.com/book/en/v2/Git-Tools-Submodules


For 2, it is a bit more convoluted.

First you fetch the commits of the other repo:

# add remote
git remote add sub <locationofsubrepo>
# fetch commits
git fetch
# create local branch with sub
git checkout -b sub_branch sub/master
# switch to master
git checkout master
# now, merge commit as a subdirectory
git read-tree --prefix=sub/ -u sub_branch

you can in the future keep pulling from sub, and it will be merged into sup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ulidtko