You might have used Git before as a version control software, by which you can maintain multiple versions of your code. But often it’s used for much more than that. Many will use it not only for versioning and collaboration, but also for deploying their code from their local machines to server (testing or production). So it’s actually become an integral tool when it comes to going live with your work.
My biggest driving force was to get rid of constantly uploading files by FTP. But let’s make it straight Git is not an ideal deployment tool. Why? For example it can’t track permissions or empty folders. Despite this I always try to make use of automated “git push” changes to live server. Yes pushing not “git pull” from local repo, just because “pull = fetch + merge” and merges can’t be guaranteed to complete without some corrections. Also you would have to run “git pull” by hand (or from a cron job), and it doesn’t require your local to be accessible by ssh.
Here are my expectations from Git:
- Deployed files – copy to the deployment folder.
- Deleted files in the git repository – delete from the deployment folder.
- Tracked files in the deployment folder after the last deployment – ignored.
- Untracked files in the deploy folder – left alone.
if someone needs more than that, it’s time to start looking for real deployment tool.
Step 1 – Create local repository
$ git init
$ git add .
$ git commit -m "First Commit"
Step 2 – Create remote repository
$ mkdir website.git && cd website.git
$ git init --bare
In “hooks/post-receive” file all the magic happens:
$ nano hooks/post-receive
GIT_WORK_TREE=/home/shell-username/example.com git checkout -f
$ chmod +x hooks/post-receive
Step 3 – Add remote repository
$ git remote add web ssh://firstname.lastname@example.org/~/website.git
$ git push web +master:refs/heads/master
This will transfer any new commits to the remote repository, where the post-receive hook will immediately update folder for you.
From now you can simply push by:
$ git push web
Be aware that you should always:
- checkout to the same deploy directory
- checkout the same branch
- use “-f”
Also keep in mind that not always it’s the best idea to keep whole website in one repository. Sometimes it’s better to create separate ones for each part of your work (e.g. for modules, themes, images). Another option is to create a repo with some git submodules.
When things go wrong
Abort changes to tracked files before checkout:
git diff --quiet || exit 1
Abort when untracked files appear:
git ls-files -o | grep >/dev/null . && exit 1