Git is a tool for tracking changes in any set of files, commonly used to coordinate work among teams of programmers during software development. Its goals include speed, data integrity, and compatibility with non-linear distributed workflows (thousands of parallel branches running on different systems).
Everyone who works in programming uses git or similar version control tools daily. In this post, we will explain a fairly common work scenario: how to connect a project to more than one repository.
How to connect a project to more than one repository
Let's imagine we have a project in the folder /home/raulsanchez/workspace/project 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 repository information and its branches:
raulsanchez@raulsanchez:~/workspace/project$ cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = git@bitbucket.org:sinapsis-team/project.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 repository of code git@bitbucket.org:sinapsis-team/other_project.git
The command for this would be:
git remote add newremote git@bitbucket.org:sinapsis-team/other_project.git
And if we go back to the git configuration file, this will have been added:
[remote "newremote"]
url = git@bitbucket.org:sinapsis-team/other_project.git
fetch = +refs/heads/*:refs/remotes/newremote/*
To complicate things a bit, let's assume that in this other repository, and it would actually be the norm, we have the same working branches: master & staging
So, how will git know which "master" branch to download if we do a "git checkout master" without any qualifiers?
A very convenient solution is to use aliases in our local configuration; we will call "remote-master" the "master" branch of the "newremote" repository, 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 configuration file, this will have been added
[branch "remote-master"]
remote = newremote
merge = refs/heads/master
And now we would have no 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"