Push-to-Deploy
September 20, 2024I recently made a cool discovery about Git that changed the way I can manage my projects: push-to-deploy. Up until now, I mostly saw Git as just a way to synchronize my local projects with GitHub or GitLab (basically version control and collaboration). My usual routine was to initialize a repository on my local machine, link it to a remote, and start pushing changes. That was the extent of what Git meant to me.
But then someone shared a great tip with me: you can actually use Git to connect two local folders, not just your project and a remote like GitHub. That means for example that you can set up a direct link between your local project and a folder on your web server, effectively making push-to-deploy possible without needing any third-party services like 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 clean and time-saving workflow that lets me skip the whole SSH process entirely.
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've got to thank the person who first introduced me to this method, it's made my workflow so much smoother, and credit noelboss for originally coming up with this method.