Merge git repo into branch of another repo

Git

Git Problem Overview


Given repo Foo and repo Bar. I want to merge Bar with Foo, but only into a separate branch, called baz.

git switch -c baz <= put the Bar repo here.

Git Solutions


Solution 1 - Git

You can't merge a repository into a branch. You can merge a branch from another repository into a branch in your local repository. Assuming that you have two repositories, foo and bar both located in your current directory:

$ ls
foo bar

Change into the foo repository:

$ cd foo

Add the bar repository as a remote and fetch it:

$ git remote add bar ../bar
$ git remote update

Create a new branch baz in the foo repository based on whatever your current branch is:

$ git switch -c baz

Merge branch somebranch from the bar repository into the current branch:

$ git merge --allow-unrelated-histories bar/somebranch

(--allow-unrelated-histories is not required prior to git version 2.9)

Solution 2 - Git

Updated with "real-life" commands:

Start from your repo directory, make sure your working copy is clean (no files changed, added or removed).


Make a new branch:

git checkout -b <my-branch>

Add the secondary remote, then fetch it:

git remote add <repo-name> git@github.com:xxx/<repo-name>.git
git remote update

Merge one of their branches in your current branch:

git merge <repo-name>/<their-branch>


If you don't know which <their-branch> you want, then go for master

If you are sure you want to accept all remote changes and avoid conflicts (overwrite yours) then you can specify -X theirs as option for git merge in the last step.

If you want to add it in a subdirectory then you should probably use git submodules

Solution 3 - Git

Using the guide from larsks, I was able to do this using SourceTree.

  1. Created a branch in the destination repository
  2. Added the source repository as a remote, by hitting the Settings button and adding the source repository.
  3. Branches from both repository now show in the branch list. I used the merge tool to merge a branch from the source repository to my new destination repository's branch.
  4. Resolved any conflicts using either SourceTree or my IDE
  5. Commit the changes in my branch.
  6. Remove the source repository from the remote list, by using the Settings button.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMilktraderView Question on Stackoverflow
Solution 1 - GitlarsksView Answer on Stackoverflow
Solution 2 - GitvinzdefView Answer on Stackoverflow
Solution 3 - GitAL - DivineView Answer on Stackoverflow