Search code examples
gitgit-subtree

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


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.


Solution

  • 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.