Consider the following scenario:
I have developed a small experimental project A in its own Git repo. It has now matured, and I'd like A to be part of larger project B, which has its own big repository. I'd now like to add A as a subdirectory of B.
How do I merge A into B, without losing history on any side?
Combining two git repositories. Use case: You have repository A with remote location rA, and repository B (which may or may not have remote location rB). You want to do one of two things: preserve all commits of both repositories, but replace everything from A with the contents of B, and use rA as your remote location.
To merge branches locally, use git checkout to switch to the branch you want to merge into. This branch is typically the main branch. Next, use git merge and specify the name of the other branch to bring into this branch. This example merges the jeff/feature1 branch into the main branch.
To combine two separate Git repositories into one, add the repository to merge in as a remote to the repository to merge into. Then, combine their histories by merging while using the --allow-unrelated-histories command line option.
If you want to merge project-a
into project-b
:
cd path/to/project-b git remote add project-a /path/to/project-a git fetch project-a --tags git merge --allow-unrelated-histories project-a/master # or whichever branch you want to merge git remote remove project-a
Taken from: git merge different repositories?
This method worked pretty well for me, it's shorter and in my opinion a lot cleaner.
In case you want to put project-a
into a subdirectory, you can use git-filter-repo
(filter-branch
is discouraged). Run the following commands before the commands above:
cd path/to/project-a git filter-repo --to-subdirectory-filter project-a
An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731
Note: The --allow-unrelated-histories
parameter only exists since git >= 2.9. See Git - git merge Documentation / --allow-unrelated-histories
Update: Added --tags
as suggested by @jstadler in order to keep tags.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With