Home > Software engineering >  How to use git subtree to create a new repo from a subdirectory
How to use git subtree to create a new repo from a subdirectory

Time:01-03

I have a git repository, and would like to use a subdirectory of it, to create a new repository. I would then like the new repository to be able to pull in changes from the parent repository subdirectory periodically; as if from an upstream repo as a repository fork. Can someone please explain the steps involved? For simplicity, let's assume I would like to use git subtree to accomplish this.

CodePudding user response:

First you need to isolate your subdirectory into its own repository, as explained in "Git Filter Repo — Splitting a Subfolder Into A New Repository" from Edward Ezekiel.
But also from "Split a subdirectory to its own repository using git filter-repo"

 git filter-repo --subdirectory-filter mySubDir/ --path-rename mySubDir/:

Create a remote repository (on GitHub/GitLab/...) and push it.

For GitHub, for instance (using gh repo create, after installing it)

cd /path/to/new/mySubDir/repo
gh repo create mySubDir --public --push

That will configure the remote and push it, in one go.

Second, add your new repository as a subfolder of your current repository, after removing said subfolder first.

git subtree add --prefix {local directory being pulled into} {remote repo URL} {remote branch} --squash
cd /path/to/repo
git rm -r mySubDir/
git commit -m "remove mySubdir"

git subtree add --prefix mySubDir https://github.com/my/mySubDirRepo main --squash

I would then like the new repository to be able to pull in changes from the parent repository subdirectory periodically

If you want to pull in any new commits to the subtree from the remote:

git subtree pull --prefix mySubDir https://github.com/me/mySubDir.git main --squash

If you want the opposite, meaning if you make a change to anything in mySubDir and want to update the remote repository:

git subtree push --prefix mySubDir https://github.com/me/mySubDir.git main
  • Related