如何从其他仓库添加 git 子模块并将其与本地文件夹合并

How to add a git submodule from other repo and merge it with local folder

我有一个特定的情况,但我没有在堆栈中找到与之匹配的答案。
我有一个 root_project ,它是基本应用程序目录,与它的远程仓库同步。

现在我在里面有一个文件夹,它被命名为oscar。我之前下载了压缩文件 oscar 并将其复制到我的 root_project 中,然后在我需要的地方对其进行了自定义。
之后我注意到,如果我需要从远程 oscar 获取更新,一旦这些更新完成,我就会遇到麻烦。

基本的想法是使用 git submodule,但我真的不知道如何根据我的需要调整它,因为我不想让我的项目崩溃并回购实验。

另外一个特定的部分是我只需要 oscar 回购中的 src/oscar,它实际上在我的 root_project 中并且可以与我在本地 oscar 文件夹,而不会丢失我已经在本地完成的事情。

对于在当前情况下如何正确使用 git submodule 的任何帮助和建议,我将不胜感激,如果可能的话,我想看看我必须采取哪些步骤才能获得预期的结果

[...] as i don't want to crash my project and repo on experimenting.

首先,您不应该害怕尝试本地存储库中的东西。只要您保留在本地副本上并且 发布实验性更​​改,您始终可以删除整个内容并从远程再次克隆它。如果您只是尝试一下,这是一种学习东西的好方法,尤其是当您打破正在进行的一切时。不要犹豫,这样做吧!

回答您的问题:我假设 oscar 作为远程存储库存在。 Git 子模块确实是管理您偶尔需要更新的子存储库的好方法。您可以找到有关如何使用子模块的好文档 here. It will be easier if you clone oscar directly from the remote via git submodule add instead of downloading and extracting a zip file first. This newly cloned submodule will of course not contain your local changes to oscar, but you can easily import them by following the steps described here

Also a specific part is that i need only src/oscar from oscar repo, that is actually in my root_project and to make it possible to merge with my changes in local oscar folder, without loosing the things i've already done locally.

这部分我没看懂。您只想添加 oscar 的子文件夹作为子模块吗?

编辑:所以你希望你的子模块只包含 oscar 存储库的一个子文件夹。您可以在使用

克隆整个存储库(通过 git submodule add)后执行此操作
git filter-branch --prune-empty --subdirectory-filter FOLDER-NAME  BRANCH-NAME 

描述了过程 here,尽管您只对第 5 点感兴趣。请注意,您必须在子模块内执行此操作,即您必须 cd 进入子模块文件夹。