DEV Community

Mpho Mphego
Mpho Mphego

Posted on • Originally published at blog.mphomphego.co.za on

How To Fork A Subdirectory Of Repo As A Different Repo On GitHub

The Story

Ever wanted to fork a subdirectory and not the whole Git/GitHub repository. Well I have, I recently had to fork a subdirectory of one of the repositories I wanted to work on without the need to fork the whole repository. In this post, I will show you how it's done.

Note: I do not think you can fork subdirectories through GitHub's web interface

The How

Clone the repo

git clone https://github.com/<someones-username>/<some-repo-you-want-to-fork>
cd some-repo-you-want-to-fork
Enter fullscreen mode Exit fullscreen mode

Create a branch using the git subtree command for the folder only

git subtree split --prefix=./src -b dir-you-want-to-fork
git checkout dir-you-want-to-fork
Enter fullscreen mode Exit fullscreen mode

Create a new GitHub repo

Head over to GitHub and create a new repository you wish to fork the directory to.

Add the newly created repo as a remote

cd some-repo-you-want-to-fork
git remote set-url origin https://github.com/<username>/<new_repo>.git
Enter fullscreen mode Exit fullscreen mode

Push the subtree to the new repository

git fetch origin -pa
git push -u origin dir-you-want-to-fork
Enter fullscreen mode Exit fullscreen mode

Fetch all remote branches in the new repository

git clone https://github.com/<username>/<new_repo>.git
cd new_repo
git checkout --detach
git fetch origin '+refs/heads/*:refs/heads/*'
git checkout dir-you-want-to-fork
Enter fullscreen mode Exit fullscreen mode

You now have a "fork" of the src subdirectory.

Merge to main/dev branch (troubleshooting)

If you ever run git merge master and get the error fatal: refusing to merge unrelated histories; run

git checkout dir-you-want-to-fork
git merge --allow-unrelated-histories master
# Fix conflicts and
git commit -a
git push origin dir-you-want-to-fork
Enter fullscreen mode Exit fullscreen mode

Reference

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay