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:
- I didn’t want to increase the size of the main repo by adding images.
- 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:
-
Clone the project elsewhere, rename the directory (e.g., repo-web) and navigate into it.
-
Checkout the branch you want to keep (
gh-pages
, for example). -
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
-
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.
-
To clear all that out:
git gc --prune=now --aggressive
-
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