Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save peter-avila/b9c1cd354947374e38e858697b7ef5d4 to your computer and use it in GitHub Desktop.
Save peter-avila/b9c1cd354947374e38e858697b7ef5d4 to your computer and use it in GitHub Desktop.

WIP Draft (untested)

Source: Splitting a subfolder out into a new repository

Source: Git Submodules vs Git Subtrees

Source: Subfolder to git repo

Creating a submodule from a subfolder of an existing repository

You can turn a folder within a Git repository into submodule by splitting it into a new repository, then adding it to the original repo.

  1. Open the terminal.

  2. Change the current working directory to the location where you want to create your new repository.

  3. Clone the repository that contains the subfolder.

     $ git clone https://github.com/_USERNAME_/_PARENT-REPOSITORY-NAME_
    
  4. Change the current working directory to your cloned repository.

     $ cd _PARENT-REPOSITORY-NAME_
    
  5. To filter out the subfolder from the rest of the files in the repository, run git filter-branch, supplying this information:

    • FOLDER-NAME: The folder within your project that you'd like to create a separate repository from.

Tip: Windows users should use / to delimit folders.

  * `BRANCH-NAME`: The default branch for your current project, for example, `master`.

  $ git filter-branch --prune-empty --subdirectory-filter _FOLDER-NAME  PARENT-BRANCH-NAME_
  # Filter the specified branch in your directory and remove empty commits
  > Rewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (xx/yy)
  > Ref 'refs/heads/_PARENT-BRANCH-NAME_' was rewritten

The repository should now only contain the files that were in your subfolder.

  1. Remove the original remote and push the pruned repo to the new remote for the submodule.

    $ git remote rm origin
    $ git remote add origin [email protected]:[username]/[submodule-repo-name].git
    $ git push -u origin master
    
  2. In the the original parent repository, remove the subfolder containing the submodule and add the new repository as a submodule.

     $ cd _PARENT-REPOSITORY-NAME_
     $ git rm sub/module/path
     $ git commit -m "Remove folders that have been split into separate repository."
     
     $ git submodule add [email protected]:[username]/[submodule-repo-name].git sub/module/path
     Cloning into ‘lib/awesomelib’…
     remote: Counting objects: 11, done.
     remote: Compressing objects: 100% (xx/yy), done.
     remote: Total 11 (delta 0), reused 11 (delta 0)
     Unpacking objects: 100% (11/11), done.
     Checking connectivity... done.
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment