Skip to content

Instantly share code, notes, and snippets.

@kobapan
Last active November 10, 2015 13:53
Show Gist options
  • Select an option

  • Save kobapan/226d3729d7ae120c17ec to your computer and use it in GitHub Desktop.

Select an option

Save kobapan/226d3729d7ae120c17ec to your computer and use it in GitHub Desktop.
github に push すると、Webhooks 経由で、ウェブサーバ側が自動で git pull して、jekyll build して、rsync する感じのあれ
<?php
header('Content-Type: application/json');
$secret = 'パスワード';
$repo = 'リポジトリの名前';
function generate_response($code) {
$response = array(
'200' => array(
'status' => 'success',
'errors' => null
),
'400' => array(
'status' => 'fail',
'errors' => array(
'code' => '400',
'message' => 'Invalid request.'
)),
'401' => array(
'status' => 'fail',
'errors' => array(
'code' => '401',
'message' => 'Could not authenticate.'
)),
'500' => array(
'status' => 'fail',
'errors' => array(
'code' => '500',
'message' => 'Internal Server Error.'
))
);
return json_encode($response[$code]);
}
function cmd ($cmd) {
exec($cmd, $arr, $res);
if ($res === 0) return true;
else return false;
}
function publish () {
$HOME = '/home/ユーザ名';
if(chdir($HOME.'/git/ほげほげ')
and cmd('export GIT_SSH_COMMAND="ssh -i '.$HOME.'/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no";'.
'git pull')
and cmd("export RUBYLIB=${HOME}/local/lib/ruby/site_ruby/1.9.3:${HOME}/local/lib/ruby;".
"export GEM_HOME=${HOME}/local/lib/ruby/gems;".
"export NODE_PATH=${HOME}/local/lib/node_modules;".
"export NODE_MODULES=${HOME}/local/bin/node;".
"export LD_LIBRARY_PATH=${HOME}/local/lib;".
"export LD_RUN_PATH=${HOME}/local/lib;".
"PATH=${HOME}/local/bin:${HOME}/local/lib/ruby/gems/bin:${PATH};".
"jekyll build --config __config.yml")
and cmd("rsync -rv _public/ ${HOME}/www")
) return true;
else return false;
}
if (!isset($_SERVER['HTTP_X_HUB_SIGNATURE'])) {
header('HTTP/1.1 400 Bad Request');
print generate_response(400);
error_log(__FILE__.' : '.__LINE__ .': HTTP/1.1 400 Bad Request');
die();
}
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$signature = substr($_SERVER['HTTP_X_HUB_SIGNATURE'], 5);
$hash = hash_hmac('sha1', $json_str, $secret);
if (($hash !== $signature) || ($json_obj->repository->name !== $repo)) {
header('HTTP/1.1 401 Unauthorized');
print generate_response(401);
error_log(__FILE__.' : '.__LINE__ .': HTTP/1.1 401 Unauthorized');
die();
} elseif (! publish()){
header('HTTP/1.1 500 Internal Server Error');
print generate_response(500);
error_log(__FILE__.' : '.__LINE__ .': HTTP/1.1 500 Internal Server Error');
die();
} else {
print generate_response(200);
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment