Detach (Move) Subdirectory into Separate Git Repository
To detach (move) a subdirectory into a separate Git repository, you can use the git subtree command. This approach allows you to preserve the history of the subdirectory. Here are the steps to achieve this:
Navigate to your repository:
Split the subdirectory into a separate branch:
Use the
git subtree splitcommand to create a new branch that contains the history of the subdirectory. Replacesubdirwith the path to your subdirectory.Create a new repository:
Initialize a new Git repository for the subdirectory.
Pull the subdirectory branch into the new repository:
Use the
git pullcommand to pull the newly created branch from the old repository into the new repository. Adjust the path to your old repository accordingly.Optional: Remove the subdirectory from the original repository:
If you want to remove the subdirectory from the original repository, you can do so and commit the changes.
Example
Assuming you have a repository with the following structure:
And you want to move /subdir to a new repository:
Navigate to your original repository:
Split the subdirectory into a separate branch:
Create a new repository for the subdirectory:
Pull the subdirectory branch into the new repository:
Remove the subdirectory from the original repository (optional):
Notes
- The
git subtreemethod preserves the commit history of the subdirectory. - Ensure you have the correct paths and branch names when running the commands.
- If you need to push the new repository to a remote server, you can follow up with
git remote add origin <url>andgit push -u origin master.
By following these steps, you will have successfully moved a subdirectory into a separate Git repository while retaining its history.