git:将现有仓库拆分为子模块

7
我只找到使用git子树来拆分存储库的方法,但我明确想要子模块。
这是一个Java maven项目。当前,所有内容都在一个maven项目和一个存储库中。我的目标是实现以下内容:
根存储库应包含主pom.xml、系统文档等。 然后应该有几个子模块,一个用于实用程序库,一个用于主应用程序等。子模块是它们自己的maven项目,并从根存储库中的主maven项目中引用。根存储库将不包含任何源代码。
我可以从当前HEAD创建新的一切,但对我来说保留提交历史记录尽可能完整非常重要。
2个回答

15

我只找到有关如何使用git子模块拆分存储库的答案。然而,我明确想要子模块。

这正是您需要做的。使用git subtree split <path> -b <branch>将“主”分为分支,然后为每个子模块添加远程并将分支推送到远程。

# split the "main repo"
git subtree split -P path -b <branch1>

# For each branch that you extract

# add remote for branch 1
git remote add submodule1 <url>

# push the submodule
git push submodule1 <branch>

一旦你设置好所有的子模块,将它们添加到"main"版本库中。

# add the submodules 
git submodule add <url>

# and once all your submodules are added commit the .gitmodules file

1
也许我只是没看到,但我在哪里实际上可以创建子模块?浏览文档,我认为我需要为每个提取的子树使用 git submodule add ... 呢? - a.ilchinger
这是我需要的 git submodule add ... ... 这是将子模块添加到您的项目中的方法,上面的代码向您展示了如何创建它们。 - CodeWizard
什么是URL?我知道一个URL,就是我的远程Git存储库的URL。那么,对于每个尚不存在的模块,我应该创建一个特定的URL吗? - kaizokun
没错,每个子模块都有一个URL。 - CodeWizard
好的,谢谢,那就是我没有理解的地方,我需要先在 Git 服务器上创建远程仓库。 - kaizokun
当然。为每个模块创建一个代码仓库,然后将其添加到GitHub。 - CodeWizard

5
# split the "main repo"
git subtree split -P path -b <branch>

# Create your repository, and get git url

# add remote for branch
git remote add submodule <url>

# push the submodule
git push -u submodule <branch>:master

# remove path
git rm -r path

# Stage and commit changes
git add -A
git commit -m 'Remove <path> for submodule replacement'

# add the submodule 
git submodule add <url> <path>

# and once your submodule is added commit the .gitmodules file 

太棒了!感谢你提供有用的答案。我的代码库中有2个分支。我在主分支上进行了子模块拆分,但是在与我的开发分支合并时遇到了问题。在拆分后,如果我尝试使用git checkout dev,会出现以下错误:error: The following untracked working tree files would be overwritten by checkout: Please move or remove them before you switch branches.有什么办法可以解决这个问题吗? - Mr.Weathers

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