How do I share a folder from one Git repository to another?

Viewed 108

I have two projects [git repos] that share a database schema, but only one of the projects actually contains the DDL SQL files. I know I could add the one containing the SQL as a subtree, but that would take over all the code and everything - all I need is the directory with the SQL files, so I can create the schema in the second project for testing using H2. I'd really rather not try to keep them synched manually [never works] - so I was hoping to simply link the /sql folder in project 1 into project 2.

I also cannot create any new repos in Git.

2 Answers

1. Submodule

Using Git's submodules, you can only link the whole repository inside another one. So one way would be to separate the whole /sql directory into an individual repository and link it as a submodule into both repositories.

In this case, changes into files of the linked repository will get pushed to the source repository.

2. Subtree

But there's also a subtree which may allow what you need. But I have never used that so you have to try it.

Check for example this page:

# Clone the target repo
git clone git@github.com:jclouds/jclouds.git
cd jclouds

# Add the source repository as a remote, and perform the initial fetch.
git remote add -f sourcerepo git@github.com:jclouds/jclouds-labs-openstack.git

# Create a branch based on the source repositories' branch that contains the state you want to copy.
git checkout -b staging-branch sourcerepo/master

# Here's where the two approaches diverge.
# Create a synthetic branch using the commits in `/openstack-glance/` from `sourcerepo`
git subtree split -P openstack-glance -b openstack-glance

# Checkout `master` and add the new `openstack-glance` branch into `/apis/openstack-glance/`. At this point, the desired result will have been achieved.
git checkout master
git subtree add -P apis/openstack-glance openstack-glance

# Clean up by removing the commits from the `openstack-glance` branch and the `sourcerepo` remote.
git branch -D openstack-glance staging-branch
git remote rm sourcerepo

In this case, changes to the linked subtree or directory won't get pushed back to the source repository, but that what you need I guess so should be fine.

There is no native feature in Git that does what you want. Two "tricks" that come to my mind:

  1. As you say you can't create a third repo to store only the shared SQL files, you could create an orphan branch in the repo that already contains the SQL files, move the files there, and use that branch as a submodule in both repos.

  2. You could combine the submodule approach with a sparse checkout to only checkout the SQL files. However, this still fetches the whole history of the submodule, it's just that no other files than the SQL files will be checked out in your working tree.

Related