Importing a subdirectory from one repo into another
When I wrote Merging multiple repositories into a monorepo, while preserving history, using
git subtree, I'd found it useful to be able to merge multiple repos into a single one. However, sometimes you don't want the whole repo, but only a subdirectory.
(After it being on my TODO list for over 6 years (!), I'm finally documenting it.)
This has recently been very useful with working to reduce the size of the dependency tree in oapi-codegen, as we've been splitting out parts of the repository into multiple repos. I wanted to retain the Git history for this, but wanted to make sure that it was only for the subset of the repository I cared about, instead of having the whole repo's history since the beginning of time.
To do this, we can follow the
git subtree option from this StackOverflow.
For instance, when doing this with oapi-codegen, I ran the following to import the
git remote add upstream --no-tags https://github.com/deepmap/oapi-codegen
git fetch upstream
git checkout upstream/master
git subtree split -P pkg/runtime -b tmp
git checkout main
git subtree add tmp -P pkg
git mv pkg/* .
git add .
git commit -m 'Flatten directory structure'