Sharing a code between two projects in git

Victor Ronin picture Victor Ronin · Jan 21, 2013 · Viewed 7.3k times · Source

I have two tightly related projects (A and B) which share some source code (S). Both of them will be released at the same time and released version should always use the same version of shared code. Shared code S will be changed reasonably often.

So, it will look sometime like this:

  • A version 1 uses S version 1
  • B version 1 uses S version 1
  • A version 2 uses S version 2
  • B version 2 uses S version 2

What is the best way to handle this with git (and/or some tools which use git)?

Here are my concerns:

  • Project A and Project B should be in separate repositories (they are related, but I don't want to have free flow of code between them)
  • If a shared code updated in one project, it should be automatically updated in another one (I don't want to have a situation when a developer forgot to do something and end up having outdate version of shared code).

As I understand one of canonical answers is "use git submodule". However, I read some criticism about this approach. I felt like it was more designed to shared libraries which rarely change.

Another approach which I read was using git subtree

And there are couple of less popular approaches: Repo, GitSlave

What would be the best approach to handle this type of code sharing?

Answer

Kalle Pokki picture Kalle Pokki · Jan 22, 2013

A very simple solution would be to use three repositories: A, B, and S. The project repositories A and B would have a check in their Makefiles to verify that the developer is using the latest code pushed to the repository, e.g.

check:
      git fetch /path/to/S master:tip
      git branch --contains tip | grep -q master

The second line will have a non-zero return value if the developer has an old version of the shared repository. This will abort the compilation with an error. The developer can then go and pull the repository manually to proceed.

Instead of checking the master branch of S, you could also check for some other branch that is defined to be always the one the developers should be using.