I had some old projects that I needed to push to a new remote. Both repositories had their git history which I wanted to retain after switching to the new remote.
Usually this would be a rather trivial task using the git remote
command.
First, create a new remote repository and leave it empty. Next set a new remote url in your local working directory, then push to the new remote, and finally cleanup the old remote:
git remote add new-origin NEW-REMOTE-URL
git remote push new-origin master
git remote remove origin
git remote rename new-origin origin
It is important that the newly created remote repository remains empty. This way, without any commits, the repositry essentially has no history yet. Without remote history, there is no diverging between the local and remote, so you can safely push.
In my case though, I had no control over the creation of the new remote repository.
So I received a remote repository that already contained a README
file.
Since there was already a commit, I ended up with 2 different git histories: one in my local folder and one in the remote repository. Two different git histories means there is not a single commit in common, so there is no basis for merging. Now when trying to pull from remote in order to update my local branches, I was getting an error saying unrelated histories cannot be merged.
What I needed to do is merge the two histories into one somehow and this is exactly what the --allow-unrelated-histories
flag does:
git pull origin develop --allow-unrelated-histories
# or
git merge origin develop --allow-unrelated-histories
According to the docs, by default git merge does not allow merging histories that have no common ancestor and the --allow-unrelated-histories
flag overrides this default.
I have to admit this use case is probably super rare, but it is awesome that git covers it anyways.