如何将git仓库中的特定文件夹添加为子模块?

63

我有一个git repo,想要添加一个子模块。问题是,这个子模块存在于另一个repo的文件夹中。我可以只将该文件夹作为子模块添加吗?


我在 Stack Overflow 上找到了一个对我有用的解决方案:https://dev59.com/uWox5IYBdhLWcg3wr2To - ItayB
3个回答

45
我最终做了以下事情:
  1. 创建一个名为“submodules”的目录。
  2. 将子模块添加到此目录中。
  3. 创建一个符号链接到子模块内特定的目录。
这样,您就可以拥有默认的Git子模块行为,并且在您的项目中仅使用整个子模块的子集。

嗯,我不知道这是否适用于我的Windows开发人员,但我们会尝试并告诉他们。 - fixmycode
5
如果你安装了GitBash并开启了"启用符号链接"权限,那么这将有效! - fixmycode
很好。除了Antora/Asciidoctor不支持符号链接 :( - mn_test347

29

如果你确实需要将其他仓库的一部分包含在自己仓库的历史中,那么使用子树合并策略比子模块更适合。

  • 将其他项目命名为“repo1”并获取它。
  • 准备记录结果为合并的后续步骤。
  • 读取“repo1”的“main”分支到子目录“repo1”中。
  • 记录合并结果。
  • 使用“subtree”进行后续合并以维护结果。
$ git remote add -f repo1 /path/to/repo1
$ git merge -s ours --no-commit --allow-unrelated-histories repo1/main
$ git read-tree --prefix=repo1/ -u repo1/main
$ git commit -m "Merge repo1 as our subdirectory"
$ git pull -s subtree repo1 main

但无论哪种情况,完整的存储库都链接到您的存储库中,而不仅仅是一个目录。
并且无法进行部分克隆

您可以尝试将该目录分离为自己的存储库,然后将其作为子模块添加,但这意味着它的历史记录将与最初来自的存储库完全分离。

现代示例将使用git filter-repo

cd /path/to/repo1
git filter-repo --path repo1SubFolder

#Move the files inside repo1SubFolderto the root
git filter-repo --subdirectory-filter repo1SubFolder/

# Go to your new repository, add a remote to the original repository
cd /path/to/repo2
git remote add repo1 /path/to/repo1

# Pull files and history from this branch into repo2 
# (containing only the directory you want to move) .
git pull repo1 main
git remote rm repo1

1
我发现你的subtree merge strategy中的这个注释特别相关:此外,如果您对其他项目进行更改,则仅使用子模块提交更改会更容易。 - Devin Rhode
1
@DevinRhode 11年后,我同意。我现在大多使用子模块。 - VonC
链接页面往往比你想象的更容易消失。如果您能在此处添加实际示例,那将是很好的。 - AaA
@AaA 非常正确。我已经在答案中包含了相关的(并且更新的)示例。 - VonC

-1
  1. 创建新分支
  2. 将所需文件移动到新分支
  3. 向超级仓库添加子模块
  4. 检出子模块到新分支

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