How to Merge Two Git Repositories While Preserving History

 
 
  • Gérald Barré

Merging two Git repositories is useful when you want to consolidate related projects into a single repository for easier management, collaboration, and version control. This is especially helpful when two repositories share a common purpose or are tightly coupled, as it simplifies dependency management and keeps all related code in one place. It also streamlines workflows by reducing the need to switch between repositories and making it easier to track changes across the combined codebase.

Git lets you merge two repositories while preserving their commit histories. This keeps the full history of both repositories intact, so you can trace changes, understand the codebase's evolution, and retain context about past modifications, authorship, and the reasoning behind specific changes.

Shell
# Clone the first repository
git clone https://github.com/meziantou/project1.git project1
cd project1

# Add the second repository as a remote and fetch it
git remote add project2 https://github.com/meziantou/project2.git
git fetch project2

# Merge the second repository into the first one
git merge project2/main --allow-unrelated-histories

# TODO Resolve any merge conflicts manually if necessary and commit the changes

# Push the merged repository to a new remote
git push origin main

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?