How to Merge Two Git Repositories While Preserving History
Merging two Git repositories can be useful in scenarios where you want to consolidate related projects into a single repository for easier management, collaboration, and version control. This approach is particularly helpful when two repositories share a common purpose or are tightly coupled, as it simplifies dependency management and ensures all related code resides in one place. Additionally, it can streamline workflows by reducing the need to switch between repositories and making it easier to track changes across the combined codebase.
Using Git, you can merge two repositories while preserving their commit histories. This process ensures that the history of both repositories remains intact, allowing you to trace back changes and understand the evolution of the codebase. By maintaining the commit history, you retain valuable context about past modifications, authorship, and reasons behind specific changes.
# Clone the first repository
git clone https://github.com/meziantou/project1.git projec1
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!