git: Split existing repository into submodules

2020-07-27 03:33发布

问题:

I only found answers on how to use git subtrees to split up a repository. However, I explicitly want submodules.

It's a Java maven project. Currently, everything is in one maven project and one repository. My goal is to achieve something like this:

The root repository should contain the main pom.xml, system documentation, etc Then there should be a few submodules, one for a utility library, one for the main application, and so on. The submodules are their own maven project, referenced from the main maven project in the root repository. The root repository will not contain any source code.

I could create everything new from current HEAD, but it is important to me that the commit history is kept as complete as possible.

回答1:

I only found answers on how to use git subtrees to split up a repository. However, I explicitly want submodules.

Thats exactly what u need to do. Split the "main" into branches with git subtree split <path> -b <branch> and then add remote for each submodule and push the branch to the remote.

# 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>

Once you have all your submodules set up add them to the "main" repo

# add the submodules 
git submodule add <url>

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


回答2:

# 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