Git webhooks
Fri, Feb 28, 2020 · 2 minute readlinuxversion controlgit
Example use of webhooks:
Automatically update a website when chages are pushed to a repository.
There are at least two ways to achieve this, both have certain requirements:
- Use a secret key which should be sufficently complex.
- The repository should be accessible without requiring credentials, either by:
- Using keys
- Caching credentials using, e.g.,
git config credential.helper store
- Using keys
Caddy git module
Include something like the following in your Caddyfile.
# /www = directory in which git clone was originally run
git /www {
repo https://github.path/to/your-repo.git/
# path = repository directory, should be below /www
path /www/your-rep
# repo branch, default is master but sprecified anyway
branch master
# webhook - URL (under docroot) and quoted secret key
hook /webhook "SuperSecretKey"
# Optional - run command after git pull
# This example runs Hugo static site generator to update site
then hugo --destination=/www/your-repo/public
}
PHP
Create a PHP file in the root of your site repository.
This version also logs it’s changes to a file in /tmp.
For a site that frequently changes you might need to disable this or otherwise maintain the log.
Note:
I would advise against using this method (or at least this particular script) as it does not validate the request.
<?php
// Based on an example from: https://getgrav.org/blog/developing-with-github-part-2
date_default_timezone_set('Europe/London');
ignore_user_abort(true);
set_time_limit(0);
$repo = '/www/your-repo';
$branch = 'master';
$output = array();
// update github Repo
$output[] = date('Y-m-d, H:i:s', time()) . "\n";
$output[] = "Git Pull\n============================\n" . shell_exec('cd '.$repo.' && git pull origin '.$branch);
// redirect output to logs
file_put_contents('/tmp/___gogs.log', implode("\n", $output) . "\n----------------------------\n", FILE_APPEND);
?>