Search code examples
gitgithubgit-submodulesgit-subtree

How can I mirror a directory in a git repo into another git repo?


I have a directory /amp in RepoA and a RepoB (populated with the contents of /amp initially). I want to mirror any changes to the /amp in RepoA into RepoB.

Is it possible ?

P.S: RepoA contains many other directories. I only want to mirror the /amp dir. Whereas RepoB is only going to have the /amp contents not any other.


Solution

  • You could use git submodules for this, the first step would be to create a repository from your dir /amp and later use it as a submodule in your other repositories.

    To make /amp a repository you could do:

    $ cd /path/to/amp
    $ git init
    $ git add .
    $ git commit -m "First commit"
    

    Now let's assume you will be using github, you could publish your repo by doing:

    $ git remote add origin git@github.com:<your-user>/amp.git
    $ git push -u origin master
    

    Now on repoA and repoB you will need to add the new amp repo as a submodule, this can be done by doing something like this:

    $ cd /path/to/repoA
    $ git submodule add -b master git@github.com:<you-user>/amp ampMirror
    

    Same for repo repoB

    $ cd /path/to/repoB
    $ git submodule add -b master git@github.com:<you-user>/amp ampMirror
    $ git commit -m "added appMirror submodule"
    

    Notice that the name I am giving to the directory within repoA and repoB is ampMirror but it can be anything you want, indeed you can use the same name by just using:

    git submodule add -b master git@github.com:<you-user>/amp 
    

    The directory structure would look something like:

    repo(A/B)
    ├── .git/
    ├── .gitmodules   <-- created after adding the submodule
    ├── foo
    └── ampMirror
        ├── .git/     <-- repo to keep/track changes for app (need to git pull)
        └── foo
    

    Now every time a change is made into your amp repo you will need to update "pull" the changes in your repositories for example:

    $ cd /path/to/repoB
    $ cd appMirror
    $ git pull
    $ cd ..    <--- get back to your project root
    $ git commit -am "update submodule" 
    

    Another way of doing this and become useful if have more than one submodule is:

    $ cd /path/to/repo(A/B)
    $ git submodule foreach git pull origin master
    $ git commit -am "updated submodules"
    

    I hope this can help to give you a better idea.