为什么 `git submodule` 每次都需要从远程仓库获取?

7
仅从SO(Stack Overflow)上“git submodule”的搜索结果数量来看,很明显这是一个常见的且容易混淆的话题,因此我将尽可能准确地解释一下。
忘记关于更新/提交/分支子模块的一切(我理解这会大大复杂化事情),为什么每次我改变分支时子模块都会被清空?据我目前的理解,这使得分支变得昂贵;如果我在机场,无法轻松/便宜地连接怎么办?我做错了什么,或者还有一些开发哲学我还不知道吗?
例如永远不会伤害:
## make a new project
$> git --version
git version 1.7.5.4
$> mkdir new_proj; cd new_proj; git init
$> touch new_file_1.txt; touch new_file_2.txt
$> git add . && git commit -m "first commit"

## move into some development branch
$> git checkout -b cool_feature
$> <hack hack hack>
# in the middle, I add a submodule
$> git submodule add https://github.com/some/other_proj.git other_proj
$> git submodule update --init
$> ls -lR
new_file_1.txt
new_file_2.txt
other_proj
other_proj/that_file
other_proj/another_file

## I have to go back to master to do some work
$> git checkout master
# Why is other_proj still around?
$> git status
Untracked: other_proj
## Fine, I'll remove it, since I want a clean working copy, because I need to do some work and commits
$> git clean -f -d
$> <work work work>

## Now I'm ready to go back to cool_feature, but my submodules are empty!
$> git checkout cool_feature

在这个时候,我应该执行git submodule update,但如果我不能/代价太高(例如,它是远程的,我没有网络访问/速度很慢),怎么办?

我想到的最好的解决方法是将我关心的所有子模块克隆到一个完全独立的位置,然后从我的本地克隆中进行子模块操作;这样可以保持子模块的低廉成本。当然,这会给团队合作带来另一层复杂性。 :/

1个回答

2
考虑到子模块只是一个指向另一个仓库提交的指针,因此执行git submodule update是有点不可避免的(为了获取与该指针相关联的内容)。
另一个解决方法是克隆您的主要仓库:
  • 一个用于 cool_feature 分支,其中您有子模块
  • 一个用于 master 分支,其中没有任何子模块
从一个分支切换到另一个分支不需要git checkout(及其相关的git submodule update),而只需要更改路径。
如果想在一个目录中工作,另一个解决方法已在 " 用 git 子模块替换第三方代码,现在我无法切换分支" 中描述:

在切换到 master 分支之前将子模块目录移出


1
感谢您的回复,以及另一种解决方法。只是...很不幸...你必须做这样的事情。我不明白为什么git不能将子模块的内容保留在本地(它是一个完整的git repo,对吧?)并在检出时将其带回。无论如何,我会再过几天留下这个问题,然后接受这个答案。干杯! - Matt
我也是这样。特别是考虑到副本通常可以在./.git/modules/**中找到。4-5年后,仍然需要做解决方法。 - jiku

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接