Unify branches of two local copies of same repository

471 Views Asked by At

I have two copies of same git repository locally. Those two copies have each their own local branches. Can I somehow "unify" those two repositories and create one which will have local branches from both of repositories?

2

There are 2 best solutions below

3
On

The solution is quite simple:

  1. From repository copy A push all the branches to the git server.
  2. Do the same from the copy B (the branches must have different names among the two repository copies).
  3. Create a third repository called C.
  4. Add two other remotes linked to copy A and B.
  5. Pull all from A.
  6. Pull all from B.
  7. Push all branches to the new repository.

Edit

We are going to work only with 2 repo for simplicity...


~/repo-A $ cd repo-A
~/repo-A $ git branch --all

*  master
   branch-1
   branch-2

~/repo-A $ git push --all
~/repo-A $ git branch --all

*  master
   branch-1
   branch-2
   remotes/origin/branch-1
   remotes/origin/branch-2

~/repo-A $ git remote -v

origin  http://host/repo-A.git (fetch)
origin  http://host/repo-A.git (push)

~/repo-A $ cd ../repo-B
~/repo-B $ git push --all
~/repo-B $ git branch --all

*  master
   branch-3
   branch-4
   remotes/origin/branch-3
   remotes/origin/branch-4

~/repo-B $ git remote add repo-A http://host/repo-A.git
~/repo-B $ git pull --all repo-A
~/repo-B $ git branch --all

*  master
   branch-1
   branch-2
   branch-3
   branch-4
   remotes/repo-A/branch-1
   remotes/repo-A/branch-2
   remotes/origin/branch-3
   remotes/origin/branch-4

~/repo-B $ git push --all
~/repo-B $ git remote remove repo-A
~/repo-B $ git branch --all

*  master
   branch-1
   branch-2
   branch-3
   branch-4
   remotes/origin/branch-1
   remotes/origin/branch-2
   remotes/origin/branch-3
   remotes/origin/branch-4

# Now you can destry, if you want, the **repo-A** and keep only the **repo-B**.

0
On

Although usually used to reference a central server like GitHub, git's "remote" concept can actually link any two repositories, including two directories on your local computer.

So if you have a copy at /srv/foo and one at /srv/bar, you could fetch all the branches from one into the other like this:

cd /srv/foo
git remote add bar /srv/bar
git fetch bar

This will then bring them in as "remote tracking branches", so a branch on the "bar" copy called "feature-42" will be accessible as "bar/feature-42". That will still be there when if you delete /srv/bar, like a branch from GitHub would still be accessible if you had no internet access.

To turn them into actual local branches, i e. access them without the "bar/" prefix, you could just check out each in turn, e.g. git switch feature-42