Extracting a git submodule from a git module

To turn a directory within a Git repository into a separate submodule and retaining its history using the Git command line client, follow these steps:

Step 1: Extract the Directory's History

  1. Navigate to your main repository's local clone. If you haven't cloned the repository locally, do so by using Git Clone

  2. Filter the directory you want to turn into a submodule to retain its history. You can use git subtree split for this purpose. For example, to extract a directory named subdir, you can use:

    git subtree split -P subdir -b temp-branch

    This command creates a new branch (temp-branch) containing the history of the changes within subdir.

Step 2: Create a New Repository for the Submodule

  1. Create a new repository on a platform like GitHub, GitLab, Bitbucket, or on your server. This repository will host the content of your submodule.

Step 3: Push the Extracted History to the New Repository

  1. Clone the new repository to your local machine:

    git clone <new-repository-url> submodule-repo cd submodule-repo
  2. Pull the extracted history from the original repository into this new repository:

    git pull <path-to-main-repo> temp-branch:main

    Here, <path-to-main-repo> is the file path to your main repository's local clone, and main is the default branch of your new submodule repository.

  3. Push the changes to the new submodule repository:

Step 4: Remove the Directory from the Original Repository and Add the Submodule

  1. Switch back to the main repository and remove the directory that you're converting into a submodule:

  2. Add the new repository as a submodule to the original repository:

Step 5: Finalize and Push the Changes

  1. Push the changes to your main repository:

Summary

This process involves:

  • Extracting the history of a directory into a new branch using git subtree split.

  • Creating a new repository for the submodule and pushing the extracted history to it.

  • Removing the original directory from the main repository and adding the new repository as a submodule.

Make sure to replace placeholders like <repository-url>, <new-repository-url>, subdir, temp-branch, and main with your actual repository URLs, directory name, branch names, and the default branch name of your repositories.