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:
cd path/to/your/repositorySplit 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.git subtree split --prefix=subdir -b subdir-branchCreate a new repository:
Initialize a new Git repository for the subdirectory.
mkdir path/to/new/repository cd path/to/new/repository git initPull 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.git pull path/to/your/old/repository subdir-branchOptional: 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.
cd path/to/your/repository git rm -r subdir git commit -m "Remove subdir after extracting it to a new repository"
Example
Assuming you have a repository with the following structure:
/your-repository
/subdir
/otherdir
And you want to move /subdir to a new repository:
Navigate to your original repository:
cd path/to/your-repositorySplit the subdirectory into a separate branch:
git subtree split --prefix=subdir -b subdir-branchCreate a new repository for the subdirectory:
mkdir ../new-subdir-repo cd ../new-subdir-repo git initPull the subdirectory branch into the new repository:
git pull ../your-repository subdir-branchRemove the subdirectory from the original repository (optional):
cd ../your-repository git rm -r subdir git commit -m "Remove subdir after extracting it to a new repository"
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.