gitsshsynchronizationgit-baregit-init

Synchronize a distant server directory with a local git repositery


I want to synchronize a directory /home/myproject of my distant machine with, as source, the directory D:\myproject\ of my local machine. I would like to use git (to also benefit from commits history, etc.)

I did this on distant machine (creation of a bare repository, see also What is the difference between "git init" and "git init --bare"?):

mkdir /home/myproject.git
cd /home/myproject.git
git init --bare

and this on local machine (with current directory D:\myproject\):

git init
git add main.py   # D:\myproject\main.py exists on local machine
git commit -m "First"
git remote add dest root@203.0.113.0:/home/myproject.git    # via ssh
git push dest master

It works, now distant server's /home/myproject.git is synchronized, but the directory /home/myproject/ (that should contain for example /home/myproject/main.py) still doesn't exist!

So I have to do this on the distant server:

cd /home
git clone myproject.git myproject

and now /home/myproject/main.py exists.

Problem: each time I do git push on local machine, it's distant server's /home/myproject.git which is updated, and not /home/myproject/.

Question: how to configure these repositories such that git push automatically updates all the files in /home/myproject such as /home/myproject/main.py, instead of only /home/myproject.git?


Solution

  • Here is an easier solution (not requiring a "bare" repository or "post-receive hook" script):

    1. On the distant machine, create the destination repository and configure it like this:

      mkdir /home/myproject && cd /home/myproject
      git init
      git config receive.denyCurrentBranch updateInstead
      
    2. On the local machine (from working directory D:\myproject\), create the source repository, and push it:

      git init
      git add main.py
      git commit -m "First"
      git remote add dest root@203.0.113.0:/home/myproject
      git push -u dest master
      

      Now /home/myproject is updated on the distant machine!

    Note: this requires git version >= 2.4. If you don't have this one, and not available in your current distribution this can help: add-apt-repository ppa:git-core/ppa; apt update; apt install git.