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.
There are two ways to do this, depending on what you expect.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With