Create a Repo from a Branch in Git: A Step-by-Step Guide

Separating a branch into a new repo in git.
Separating a branch into a new repo in git.
Other languages: Español

You might find yourself needing to extract a branch from a git repo to create a new one, while preserving its commit history.

This was the case for one of my projects npkill. Previously, on the main repo, I had its website on the gh-pages branch. This was sufficient since the website was quite basic. However, I recently decided to rebuild it with Astro, and I thought it would be better to have it in a dedicated repo mainly for two reasons:

  1. I didn’t want to increase the size of the main repo by adding images.
  2. It seems impractical to have an independent branch of the main project. It eventually causes issues in the long run.

Separating the Branch and Creating the New Repo

To create a new repository from a branch:

  1. Clone the project elsewhere, rename the directory (e.g., repo-web) and navigate into it.

  2. Checkout the branch you want to keep (gh-pages, for example).

  3. Delete all other branches (you can view them with git branch). If there are only a few, you can delete them manually, but this command is more efficient:

    git branch | grep -v "gh-pages" | xargs git branch -D
                            # ↪ Branch you want to keep
  4. Also delete all tags with:

    git tag | xargs git tag -d

    We might think we’re done, but there’s one more crucial step. Git still holds onto “garbage” data that we don’t need, mainly because it will occupy unnecessary space.

  5. To clear all that out:

    git gc --prune=now --aggressive
  6. Finally, remove remote references. If you only have the default (origin):

    git remote rm origin

At this point, you’ll have a new repository with only the history and information related to the current branch, as if nothing else ever existed.

Cleaning Up the Initial Repo

Now that the new repo is created, you can delete the separated branch from the initial repo. To do this:

git branch -D gh-pages  # Delete local branch
git push origin --delete gh-pages  # Delete remote branch