Skip to content

Instantly share code, notes, and snippets.

@lejenome
Last active October 26, 2019 08:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lejenome/2ee7f1f47b9800140c57b51c1474439f to your computer and use it in GitHub Desktop.
Save lejenome/2ee7f1f47b9800140c57b51c1474439f to your computer and use it in GitHub Desktop.
<?php
// Webhook code to update repo clone and execute required deployement code when new commit was pushed
// Webhook content-type should be set to application/json and a random secret code should be set too.
// Secret Random Code You set on github webhook settings
const SECRET_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
if (! in_array($_SERVER['HTTP_X_GITHUB_EVENT'], ['push', 'ping'])) {
throw new Exception('Request event should be either "push" or "ping"!');
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
$hash = hash_hmac('sha1', file_get_contents('php://input'), SECRET_TOKEN, false);
if ($_SERVER['HTTP_X_HUB_SIGNATURE'] == 'sha1=' . $hash) {
$json = json_decode(file_get_contents('php://input'), true);
if(!is_array($json)){
throw new Exception('Received content contained invalid JSON!');
}
$commands = array();
if ($json['repository']['full_name'] == 'USERNAME/REPO1-DJANGO-APP') {
$commands = array(
'whoami',
'cd /PATH/TO/SITE1 && git pull',
'cd /PATH/TO/SITE1 && git status',
// 'cd /PATH/TO/SITE && git submodule sync',
// 'cd /PATH/TO/SITE1 && git submodule update',
// 'cd /PATH/TO/SITE1 && git submodule status',
'cd /PATH/TO/SITE1 && bash -c "source env/bin/activate && pip3 install -r requirements.txt"',
'cd /PATH/TO/SITE1 && bash -c "source env/bin/activate && python3 manage.py migrate --noinput"',
'cd /PATH/TO/SITE1 && bash -c "source env/bin/activate && python3 manage.py collectstatic --clear --link --noinput"',
'kill -HUP $(pidof uwsgi) && echo "Server reloaded" || echo "Can not reload the server"',
);
} else if ($json['repository']['full_name'] == 'USERNAME/REPO2-STATIC-WEBSITE') {
$commands = array(
'whoami',
'cd /PATH/TO/SITE2 && git pull',
'cd /PATH/TO/SITE2 && git status',
);
} else {
throw new Exception('Repo is not in the list');
}
// Run the commands for output
foreach($commands AS $command){
// Run it
try {
$tmp = shell_exec($command);
} catch (Exception $e) {
$tmp = "ERROR!\n";
$tmp = 'Caught exception: '. $e->getMessage(). "\n";
}
// Output
echo "sh> $command\n";
echo htmlentities(trim($tmp)) . "\n";
}
} else {
throw new Exception('Wrong signature hash!');
}
?>
@lejenome
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment