9

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:

This is my merged result.

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.

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

aynber
  • 22,380
  • 8
  • 50
  • 63
Dimitri Dewaele
  • 10,311
  • 21
  • 80
  • 127

1 Answers1

3

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)

Graham
  • 7,431
  • 18
  • 59
  • 84
Dunno
  • 3,632
  • 3
  • 28
  • 43
  • Thanks for the correct anwer. One minor problem: the rebase of RepoA makes me loose the merge history. See the image above (I added the current status in above). Is it possible to keep this? – Dimitri Dewaele Feb 13 '17 at 13:36
  • @DimitriDewaele try the `--preserve-merges` option of `rebase` – Dunno Feb 13 '17 at 14:19
  • 1
    As noted in @DimitriDewaele's follow-up question, `rebase` really isn't what you want to use for this: http://stackoverflow.com/a/42457384/54249 – dahlbyk Feb 25 '17 at 14:54