Git is a tool for tracking changes to any set of files, often used to coordinate work between teams of programmers during software development. Its goals include speed, data integrity, and support for distributed non-linear workflows (thousands of parallel branches running on different systems).

All of us who are dedicated to programming use git or similar version control tools on a daily basis. In this post we are going to explain a fairly common work scenario: how to connect a project to more than 1 repository.

How to connect a project to more than 1 repository

Let’s imagine that we have a project in the /home/raulsanchez/workspace/project folder already synchronized with a bitbucket repository git@bitbucket.org:sinapsis-team/project.git
In this repository we have 2 working branches: master & staging. If we look at the git configuration file we would have the information of the repository and its branches:
raulsanchez@raulsanchez:~/workspace/proyecto$ cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote “origin“]
url = git@bitbucket.org:sinapsis-team/proyecto.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch “master”]
remote = origin
merge = refs/heads/master
[branch “staging”]
remote = origin
merge = refs/heads/staging
Now we want to add another code repository git@bitbucket.org:synapsis-team/another_project.git
The command for this would be:
git remote add newremote git@bitbucket.org:sinapsis-team/otro_proyecto.git
And if we go back to the git config file now this will be added:
[remote “newremote“]
url = git@bitbucket.org:sinapsis-team/otro_proyecto.git
fetch = +refs/heads/*:refs/remotes/newremote/*

To complicate it a bit, we are going to assume that in this other repository, and in reality it would be usual, we have the same working branches: master & staging

So how will git know which “master” branch to check out if we do a plain “git checkout master”?

A very convenient solution is to use aliases in our local configuration, we are going to call the “master” branch of the “newremote” repository “remote-master”, so we will have it differentiated from the “master” branch of the original repository:

git switch -c remote-master newremote/master
And if we go back to the git config file now this will be added
[branch “remote-master”]
remote = newremote
merge = refs/heads/master
And now we would no longer have a problem moving between the branches of the repositories
If we want to download “master” from the original repository we would do a “git checkout master” and if we want to download “master” from the second repository we would do a “git checkout remote-master”