我有一个包含几个子模块的存储库。我想添加其他一些,对我来说最快的方法是使用
.gitmodules
(我认为这应该明确允许任何类型的子模块管理)。
但是,当编辑此文件并添加子模块时,在
git submodule init
之后,没有添加任何内容(修改之前已经存在的子模块除外)。
是否有任何解决方案可以在不经过
git submodule add
的情况下添加子模块(即只需编辑.gitmodules
文件,然后git submodule update --init
)?
也就是说,以下工作流程应自动添加子模块“foo/bar”:
Add the following to .gitmodules:
[submodule "foo/bar"]
path = foo/bar
url = https://example.com/foo.git
Run the following command after saving:
git submodule init
git submodule update
Expected result:
submodule 'foo/bar' automatically gets added
it is also updated (the update command)
当您添加 Git 子模块时,Git 会创建
.gitmodules
文件,并且对于名为 git-submodule
的子模块将添加如下内容:
[submodule "git-submodule"]
path = git-submodule
url = https://github.com/TomasHubelbauer/git-submodule
在该文件中的现有内容之后,将相同内容添加到
.git/config
。
在
.git/modules
中创建以子模块命名的子模块文件夹。
该文件夹与实际子模块存储库的 .git
目录几乎相同,但它不包含实际的 objects
(而是将子模块数据签出到其目录,其元数据位于此处)。
这意味着理论上,您可以手动添加子模块而不使用
git submodule add
,但您必须重新创建所有这些配置文件。
但人们仍然可以想象将子模块存储库克隆到一个单独的目录并将其 .git
复制到此目录。这可能有用。
但是,添加子模块也会更改索引,
.git/index
,因此您还必须手动更新此哈希,此时,您正在重新实现 Git,但是是手动的。
因此,我认为手动添加 Git 子模块不太现实。
是的,正如您所描述的,一旦您添加子模块,它就会被添加到您的
.gitsubmodule
文件中。
但是,除非您确切知道自己要做什么,否则最好使用 CLI 命令,因为可能有一些您不熟悉的内容,例如:
编辑完子模块文件后,您将需要运行:
git submodule init
git submodule update
手动添加将不起作用。
运行添加子模块并观察
.git
文件夹的变化。您将看到一个名为 module
的新文件夹,其中包含您的子模块名称。
这就是为什么您不应该手动执行此操作。
既然已经确定 Git 管理
.gitmodules
但不从中读取新条目,这里有一个注释,以防它对面临此问题的其他人有所帮助。
它会遍历
.gitmodules
文件,查找以 [whitespace]url =
开头的行,并执行 git submodule add
,后跟后面的 URL。它假设您要创建与相应存储库同名的子模块。
cat .gitmodules | sed -n 's/^\s*url = \(\S*\) */git submodule add \1/p' | bash
说明:
cat .gitmodules # output file content
sed -n # output only the relevant lines
's/regEx/replacement/p' # print the 'replacement' of the 'regEx'
^\s*url = # look for lines starting with [whitespace]url =
# but not, e.g., with #[whitespace]
\(\S*\) * # capture all characters, ignore trailing [space]
git submodule add \1 # append the captured URL to the git command
bash # execute the command
省略
| bash
部分,仅打印命令而不执行它们。根据您的喜好修改 git 命令。执行成功后,可以通过git submodule update --remote
查看.gitmodules
中可能指定的分支/修订。