Nested Git repositories?

Can I nest Git repositories? I have:

 /project_root/
 /project_root/my_project
 /project_root/third_party_git_repository_used_by_my_project

Does it make sense to git init/add the /project_root to ease management of everything locally or do I have to manage my_project and the 3rd party one separately?


You may be looking for the Git feature called submodules. This feature helps you manage dependent repositories that are nested inside your main repository.


Place your third party libraries in a separate repository and use submodules to associate them with the main project. Here is a walk-through: Git Tools - Submodules (Pro Git book, 2nd.)

In deciding how to segment a repo I would usually decide based on how often I would modify them. If it is a third-party library and only changes you are making to it is upgrading to a newer version then you should definitely separate it from the main project.


Just for completeness:

There is another solution, I would recommend: subtree merging.

In contrast to submodules, it's easier to maintain. You would create each repository the normal way. While in your main repository, you want to merge the master (or any other branch) of another repository in a directory of your main directory.

$ git remote add -f ThirdPartyGitRepo /project_root/
$ git merge -s ours --no-commit ThirdPartyGitRepo/master
$ git read-tree --prefix=third_party_git_repository_used_by_my_project/ -u ThirdPartyGitRepo/master
$ git commit -m "Merge ThirdPartyGitRepo project as our subdirectory"`

Then, in order to pull the other repository into your directory (to update it), use the subtree merge strategy:

$ git pull -s subtree ThirdPartyGitRepo master

I'm using this method for years now, it works :-)

More about this way including comparing it with sub modules may be found in this git howto doc.


You could add

/project_root/third_party_git_repository_used_by_my_project

to

/project_root/.gitignore

that should prevent the nested repo to be included in the parent repo, and you can work with them independently.

But: If a user runs git clean -dfx in the parent repo, it will remove the ignored nested repo. Another way is to symlink the folder and ignore the symlink. If you then run git clean, the symlink is removed, but the 'nested' repo will remain intact as it really resides elsewhere.