Notes to Self: git filter-repo

gmb published on
2 min, 257 words

An image of a complex highway intersection in Dubai Photo by Nick Fewings on Unsplash

This is one of those writing-it-down-so-I-know-where-it-is blog posts.

git filter-repo is an incredibly useful utility for doing various things to git repositories. It’s been particularly handy for me when merging repos together - or splitting them apart.

Here’s how to handle those two cases.

Merging two repositories together

Let’s say we have two repositories: ProjectA and ProjectB. We want to move ProjectA inside of ProjectB, under the /ProjectA directory.

First, create a new, clean clone of project A’s repo

git clone <repo URL> project_a

Then, run filter-repo to put everything into one directory.

cd project_a
git filter-repo --to-subdirectory project_a

Then add the project_a repo as a remote on project_b’s repo, and merge the two:

cd ../project_b
git remote add project_a ../project_a
git fetch project_a
git merge --allow-unrelated-histories project_a/main

Splitting a subdirectory into its own repository

Again, we need to create a fresh clone of the project from which we’re splitting out a subdirectory, because we’re going to do some history rewriting.

git clone <url> project_c
cd project_c
git filter-repo --path services/subdir-to-split
git mv services/subdir-to-split/*
git commit -m "Move all files to the top level."