I often forget the exact procedure for merging one Git repository into
another. Let’s say I need to merge the source
repo into the destination
repository under the target
directory. I assume I don’t need to
preserve the source
for this example.
I start with moving everything in the source
repo into the target
folder within:
$ cd /path/to/source
$ mkdir target
$ git mv -k * target
$ git mv .gitignore target # optional
$ git commit -m 'Prepare the repo for merging'
-k
flag skips actions that would produce an error so Git will not try
to move target
or .git
folders. I might need to move .gitignore
manually. If I intend to use the source
repository remotely, I’ll need
to push the changes before proceeding further.
Now I can create an additional remote in the destination
repository:
$ cd /path/to/destination
$ git remote add source /path/to/source
Alternatively, I can use the SSH or HTTP remote:
$ git remote add source git@github.com:account/source.git
Regardless of the method, I should see the remotes now:
$ git remote -v
origin git@github.com:account/destination.git (fetch)
origin git@github.com:account/destination.git (push)
source /path/to/source (fetch)
source /path/to/source (push)
The next step is to fetch the remote into the destination
repository
and create a local branch for it:
$ git fetch source
$ git branch source source/main
Branch 'source' set up to track remote branch 'main' from 'source'.
Let’s merge the branch now. Allowing unrelated histories is necessary
to avoid the refusing to merge unrelated histories
Git error.
$ git merge source --allow-unrelated-histories
Finally, we can remove the unnecessary remote and branch:
$ git remote remove source
$ git branch -d source