How to split a repository with subfolders into separate repositories for each subfolder?

Viewed 16

I have a local repository that includes multiple projects in separate subfolders, and I want to split it into separate, project-specific repositories without altering the actual folder structure. Here's what the folder tree currently looks like:

bigfolder/
    .git/
    project1/
        subfolder1/
        subfolder2/
    project2/
        subfolder1/
        subfolder2/

What I want instead is this:

bigfolder/
    project1/
        .git/
        subfolder1/
        subfolder2/
    project2/
        .git/
        subfolder1/
        subfolder2/

I don't want to delete the top folder or move the project folders out from under it. I just want to have smaller, project-specific repositories that preserve the commit histories of the files in each project's folder.

I tried following the directions in this article on GitHub Docs, Splitting a subfolder out into a new repository, but when I cloned the bigfolder/ repository into the project1/ folder, it copied everything inside bigfolder into the project1 folder, including all of the project folders. Using git filter-repo deleted the files inside the all newly created project folders except the new project1 folder, but it left the folder tree intact. What am I doing wrong? Thanks in advance!

1 Answers

You can use git subtree to split a subdirectory into a separate repository. The process might look like this.

  1. For each project directory, use git subtree split to move the history for that directory into an isolated branch:

    ref=$(git subtree split --prefix=project1)
    git branch project1-split $ref
    

    Repeat this for each project directory. This will split the history for each directory into a separate branch.

  2. Now that you have that, you can re-create your directory hierarchy:

    cd ..
    mkdir new-big-directory
    cd new-big-directory
    git clone -b project1-split ../big-directory project1
    git clone -b project2-split ../big-directory project2
    

    This will get you your requested layout. You may want to rename the branches at this point:

    git -C project1 branch -m project1-split main
    git -C project2 branch -m project2-split main
    
Related