Wednesday, April 3, 2019

git synchronize repositories

It happens that an external Git repository has to be mirrored internally in a corporate git repository. This cloning and mirroring should include branches, tags, commit history etc. and be one-way (internal changes are lot upon synchronization)

Luckily you don't have to write special scripts, all is provided by git:


https://help.github.com/en/articles/duplicating-a-repository



Let's make an experiment

in github I create a "gitclonesource" and a "gitclonedestination" empty repositories

mkdir gitclonetests
cd gitclonetests


#let's prepare the source
mkdir gitclonesource
cd gitclonesource
git init
echo "ciao" > README.md
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/vernetto/gitclonesource.git
git push -u origin master

#create branch
git checkout -b mybranch
echo "hello" >> mybranch.txt
git add mybranch.txt
git commit -am "added mybranch.txt"
git push --set-upstream origin mybranch

#create tag
git checkout master
git tag -a v1.4 -m "my version 1.4"
git push --tags



#now clone source and push to destination with all branches and tags
cd ..
#this will create a folder gitclonesource.git
git clone --bare https://github.com/vernetto/gitclonesource.git
#when you cd, you will see a message BARE:master if using Git bash
cd gitclonesource.git/
git push --mirror https://github.com/vernetto/gitclonedestination

Counting objects: 7, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (7/7), 600 bytes | 200.00 KiB/s, done.
Total 7 (delta 0), reused 0 (delta 0)
To https://github.com/vernetto/gitclonedestination
 * [new branch]      master -> master
 * [new branch]      mybranch -> mybranch
 * [new tag]         v1.4 -> v1.4




and, lo and behold, in the gitclonedestination I can find my branch and the tag! All cloned in one go!

at this point you can cleanup the gitclonedestination.git:

cd ..
rm -rf gitclonedestination.git








No comments: