Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two Git repositories and keep the master history

Tags:

git

merge

master

I need to merge two Git repositories into a brand new, third repository. I followed the following instructions and they work, but the result is not what I expected. Merge two Git repositories without breaking file history

Look at this:

Git Merge operation

The master is not aligned.

  • Is it possible to merge everything onto the same master?
  • I would like to have a clean history on the master.

You are free to use my example repository's on GitHub:

  • https://github.com/DimitriDewaele/RepoA
  • https://github.com/DimitriDewaele/RepoB

This is my merged result.

  • https://github.com/DimitriDewaele/Repo

This is the situation that I would like to have: (painted solution!!!)

Painted solution!!

How I got to the the current situation:

# Assume the current directory is where we want the new repository to be created
# Create the new repository
git init

# Before we do a merge, we have to have an initial commit, so we'll make a dummy commit
dir > Read.md
git add .
git commit -m "initial commit"

# Add a remote for and fetch the old RepoA
git remote add -f RepoA https://github.com/DimitriDewaele/RepoA

# Merge the files from RepoA/master into new/master
git merge RepoA/master --allow-unrelated-histories

# Do the same thing for RepoB
git remote add -f RepoB https://github.com/DimitriDewaele/RepoB

# Merge the files from RepoB/master into new/master
git merge RepoB/master --allow-unrelated-histories

All help is appreciated!

UPDATE: ANSWER

The correct answer is to rebase, instead of merge.

  • https://github.com/DimitriDewaele/RepoMerged

Code:

# Rebase the working branch (master) on top of repoB
git rebase RepoB/master

# Rebase teh working branch (master with RepoB) on top op repoA
git rebase RepoA/master

One problem remains. The 2nd repo loses the parent view. I posted a follow-up question for this: Merge two Git repos and keep the history

enter image description here

like image 848
Dimitri Dewaele Avatar asked Feb 10 '17 14:02

Dimitri Dewaele


1 Answers

It's easy, instead of merging use rebase. Assuming you want to have repoA/master first just do (after fetching and adding remotes)

# starting on master
git rebase RepoB/master # place master on top of masterB
git rebase RepoA/master # place master (with masterB) on top of masterA

Note that rebases are potentially destructive and a bit unintuitive at first, so I strongly recommend reading about them first (SO documentation in the link above is a good place to start)

like image 73
Dunno Avatar answered Oct 20 '22 20:10

Dunno