git-subtree
is a script designed for exactly this use case of merging multiple repositories into one while preserving history (and/or splitting history of subtrees, though that seems to be irrelevant to this question). It is distributed as part of the git tree since release 1.7.11.
To merge a repository <repo>
at revision <rev>
as subdirectory <prefix>
, use git subtree add
as follows:
git subtree add -P <prefix> <repo> <rev>
git-subtree implements the subtree merge strategy in a more user friendly manner.
For your case, inside repository YYY, you would run:
git subtree add -P ZZZ /path/to/XXX.git master
The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a
will show you all the changes (if any) except those in the merged history. You can do:
git log --follow -- a
but that won't show the changes other then in the merged history.
In other words, if you don't change ZZZ
's files in repository XXX
, then you need to specify --follow
and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.
More on it here.