Push-to-Deploy

Github to local repository

Recently, I made a cool discovery about Git that changed the way I manage my projects: "push-to-deploy." Before, I had only used Git as a tool to link my projects to remote repositories on platforms like GitHub or GitLab. It was a straightforward process where I would initialize a Git repository on my local machine, connect it to a GitHub repository, and push my code for version control and collaboration. And I've always thought of Git in terms of these services.

folder 1 to folder 2

Then, someone shared a valuable tip with me (that opened up a new world of possibilities!): you can actually use Git to establish a link not just between your local project and a remote Git service, but also between two local folders. This means you can create a direct connection between a project on your local machine and, say, a folder on your web server, effectively enabling "push-to-deploy" without needing to rely on third-party hosting platforms.


I started using this approach to link my local development folders directly to the folder where my website is hosted. Now, when I make changes in my local project, I can simply push those changes, and they are directly deployed to my website. It's a real game-changer.


The setup is also quite straightforward. You first need to access your website folder, and do the following:

     
$ git init --bare name.git
$ cd name.git/hooks
$ touch post-receive
$ chmod u+x post-receive
    

and write in the post-receive file the following:

    
#!/bin/bash

TARGET="../"
GIT_WORK_TREE="../"
BRANCH="master"

while read oldrev newrev ref
do
    # only checking out the master (or whatever branch you would like to deploy)
    if [ "$ref" = "refs/heads/$BRANCH" ];
    then
        echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
        git --work-tree=$TARGET checkout -f $BRANCH
        git log --pretty="%h %ad (%cr)%x09 %an: %s" --date=short > ../git_commit_log.txt
    else
        echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
    fi
done
    

Your remote is therefore all set. You need now to go to your local repository, initialize a .git, and add a remote as the following:

     
$ git init
$ git remote add yourremotename yourlinktothewebrepository
    

And voilà!

It allows direct communication between two directories, automating the deployment process with each git push. I have to give a huge shout-out to the person who introduced me to this method: it's made my workflow up until now so enjoyable.


I'd like to credit noelboss for the method.