Importing a subdirectory from one repo into another

Featured image for sharing metadata for article

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 pkg/runtime subdirectory:

#
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'

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #git #git-subtree #command-line.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.