Local files shared between two projects stored in git

73 views Asked by At

I am working on two different web sites, each with its own git repository. I have some generic code (PHP and JavaScript) which is common to both sites, and which I keep in a separate libs folder on my development machine, using a symlink so that both local web sites believe that this libs folder is at the root of the site.

I would like to manage the libs folder with git, too. I can imagine two different approaches:

  • Two remote copies of the libs folder, one in each site repo
  • A third git repository, just to manage the libs folder, with a way for the two remote site repos to know about the existence of this libs repo, so that all is tracked together.

I would appreciate help in deciding which of these two options is more reliable (or if there is an even better option). I would also be grateful for help in understanding how to set up the chosen option.

1

There are 1 answers

0
Nick Volynkin On

This is what git submodules were made for (see also in Pro Git).

libs is a separate code entity. It is shared between two (and possibly more) projects and can be versioned on its own. A perfect candidate for a submodule.

To do in project A:

  1. Remove the symlink and leave files only in project A. ( Git will probably not catch the changes in project B.)
  2. Detach (move) subdirectory into separate Git repository.
  3. Push the new submodule to its own remote. You can use any Git hosting (Bitbucket is good for free closed repos) or a local folder (secure, but vulnerable to moves and renames).

To do in project B:

  1. Commit the loss of data. git add -u, git commit -m'detached libs'
  2. Add that submodule from remote: git submodule add <repo-url> [<local path>]

Now you can check how it works, pushing and pulling from both repos.

Extra questions:

Why not just clone submodule in B from submodule in A?
This makes a more independent and flexible structure. What if you will have N projects? What if then you want to delete A? What if you want to move A in your filesystem? The scheme will break.

Why not just initiate both submodules with git-subtree?
Commit's sha1 depends also on creation time. So the two submodules will have perfectly equal contents (and matching sha1-s for blobs and trees) but completely different history. You will have to merge them, which is extra work.