Mikhail Maltsev
Mikhail Maltsev

Reputation: 1678

Synchronizing two remote git repositories

Suppose, I have the following setup:

  1. There is a git repository (let's call it "upstream") of some project (actually it's a mirror of an SVN repository, but I hope that it won't introduce any complications). I have read-only access to it (and of course, I have no access to the server to install any hooks, etc).
  2. I also have a personal Git repository, which is accessible via SSH. Let's call it "mirror". It should contain a copy of upstream with my personal branches.

I want to copy all updates from upstream to the mirror (presumably using some cronjob or, say, periodic task in Jenkins, i.e. copying should be done from a different machine, than the one on which the mirror resides). My branches will always be different from ones in upstream, so no conflicts should occur (otherwise the script should fail, but it must not overwrite any local branches). All "heads" should be updated.

I found this script which does almost what I need, but it seems to work only for "symmetric" case (i.e. writing to all repos) and fixing it probably would require too much "diving" into git man.

I would appreciate a working solution (of course I don't expect that someone would write another 300-line script for me, but maybe it's already written, or maybe it's actually easier than I think) or some hints on fixing the script mentioned above.

Upvotes: 1

Views: 1343

Answers (1)

BoomShadow
BoomShadow

Reputation: 962

Yeah, that script you found looks good, but it's a bit too big for your needs, considering you just want to pull 1 single repository. You should be able to accomplish that with much fewer lines of code.

Pretending this is a new project, this is what you would run on your server that will be hosting the sync script:

git clone [email protected]:some_user/some_project.git
git remote add mirror ssh://[email protected]_url.com/some_project.git

That will do the initial clone down of the read-only application. Then, it sets up your backup location as another remote called "mirror". You can actually call it anything you like.

Then, here is a bash script to only update your sync location when the origin changes. You can put this on a simple cron job:

#! /bin/bash
cd /path/to/git/repo/
if [ "`git pull origin`" == "Already up-to-date." ]
then
    echo "Nothing to update!"
else
    git push mirror
fi

I tested this on a project that I have on my Github and my private Gitlab server. It worked successfully!

Upvotes: 2

Related Questions