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

post image

3 Min Read

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 forking 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<username>/<my-repo>
cd my-repo

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

git subtree split --prefix=./src -b fork-src-dir
git checkout fork-src-dir

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 my-repo
git remote add upstream<username>/<new_repo>.git

Push the subtree to the new repository

git fetch origin -pa
git push -u origin fork-src-dir

Fetch all remote branches in the new repository

git clone<username>/<new_repo>.git
cd new_repo
git checkout --detach
git fetch origin '+refs/heads/*:refs/heads/*'
git checkout fork-src-dir

You now have a “fork” of the src subdirectory.