首页 > 解决方案 > 我可以在同一个存储库中使用 git 子模块吗?

问题描述

在我的项目中,有一个包含常用工具的文件夹,我想将这些工具包含在我的每个应用程序组件中。我只想要它的一个主版本,我希望其余的副本像往常一样用 git 命令更新。有没有办法在将所有内容保存在同一个存储库中的同时做到这一点?我知道子模块可以与多个存储库一起使用,但它似乎不适用于仅与单个存储库一起使用。有人对此事有任何见解吗?

标签: gitrepository

解决方案


You may want to look into git subtree. Have a look at these two articles :

Its documentation is not served on git-scm.org (I couldn't say why), you can read it by typing git help subtree, or by reading it from the source code in git's repo :


Technically, you can include a repo within itself as a submodule ; the unusual stuff would come from :

  • the commits that would be checked out at the submodule's directory,
  • the branch names,
  • the history of the commts for the submodule.

Suppose your code looks like this :

Readme.md
libs/util/fileA.py
libs/util/fileB.py
src/main.py

and you would like to have the content of libs/util/ as a "self hosted" submodule.

  1. about the commits for the submodule :

This would mean that the complete content of a certain commit of your repo should be :

fileA.py
fileB.py

You would have, in the same repo, commits that represent "the full project" and commits that represent "just the util lib" sitting one next to another.
This is perfectly manageable, just surprising at first.

  1. about the branch names :

since your repo probably already has a branch named master which represents the state of your "complete" project, you can't use that name for a branch of the "submodule" part.

The simplest way would be to choose a set of names dedicated to that submodule (for example : util/*) and stick to it.

  1. about the history :

It wouldn't make much sense to have in the same branch commits for the complete repo and commits for the submodule only. The branches dedicated to the submodule would have no relation with the branches of the "complete" project.

Again : git can perfectly manage that. Here is one way to create such a starting branch in your repo :

# from your repo's 'master' branch :
git checkout -b util/master
git filter-branch --subdirectory-filter  libs/util

When you look at how git-subtree works, it allows you to handle the same kind of setup : unrelated branches stored within the same repo, and checking out a sub branch at a location you choose.

Its main advantage is : since it was intended to work that way from the beginning, the commands will probably give you less friction, and less way to mess things up in your repo.


推荐阅读