Skip to content

Instantly share code, notes, and snippets.

@mugifly
Last active December 14, 2015 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mugifly/5087897 to your computer and use it in GitHub Desktop.
Save mugifly/5087897 to your computer and use it in GitHub Desktop.
GitHub Webhook receiver & updater cgi (for Hosting-web-server)
#!/usr/bin/env perl
# GitHub Webhook receiver & updater cgi (for Hosting-web-server)
# https://gist.github.com/mugifly/5087897/
use strict;
use warnings;
use utf8;
use lib 'lib'; # for local lib directory
use CGI;
use JSON::PP;
our $GIT_PATH = '/home/xxx/bin/git';
our $TARGET_DIR = '/home/xxx/www/YOUR_GIT_CLONED_DIR/';
our $TARGET_REPONAME = 'origin';
our $TARGET_BRANCH = 'master';
our $q = new CGI;
load_payload();
git_pull();
print "Content-type: text/html\n\n";
print "OK";
exit;
sub load_payload {
unless(defined($q->param('payload'))){
error('Invalid parameter');
}
my $payload = JSON::PP::decode_json($q->param('payload'));
if ($TARGET_BRANCH ne "" && $payload->{ref} ne 'refs/heads/'.$TARGET_BRANCH){
error('Not target refs');
}
}
sub git_pull {
chdir($TARGET_DIR);
`$GIT_PATH fetch $TARGET_REPONAME $TARGET_BRANCH`;
`$GIT_PATH reset --hard FETCH_HEAD`;
}
sub error {
my $msg = shift;
print "Content-type: text/html\n\n";
print "Error:".$msg;
exit;
}

github_webhook_updater.pl

GitHubのWebhookを受け取り、それをもとにローカルのgitディレクトリを更新するための、とても簡単(もとい、手抜き)なスクリプトです。

レンタルサーバ上のWebサイトを、GitHubのリポジトリで管理している場合などに使います。 CGIとして配置しておけば、GitHubにプッシュするだけで自動更新されます。Pure-perlなCGIですので、レンタルサーバ上で動作する...でしょう。

必須ライブラリ

  • perl 5.x
    • CGI (恐らく、ほとんどのレンタルサーバに導入済み)
    • JSON::PP (Pure perlなJSONライブラリです。)
  • git command

利用手順

あくまで確認一例であり保証するものではありません。 契約プランなどの規約に違反していないか、ご自身で確認し、自己責任でご利用ください。

  • ○○○のレンタルサーバ スタンダード
    1. gitコマンドをシェルからインストール。
    2. 目的のプロジェクトを公開ディレクトリにgit clone。(公開リポジトリなら、Read-onlyなgitスキームURLからcloneしても十分かと思います。)
    3. CGIから書き換えできるようにディレクトリのパーミッションを設定。
    4. 本スクリプトを適当な公開ディレクトリ /home/xxx/www/yyy/ へ設置。(git cloneしたディレクトリ下でも大丈夫です。)
    5. JSON::PP モジュールを /home/xxx/www/yyy/lib/ に保存。もしくはCPANシェルでインストール。
    6. 本スクリプト内のperlパスを編集(=> #!/usr/local/bin/perl)。 さらに、変数を編集:
      • $GIT_PATH = gitコマンドのフルパス
      • $TARGET_DIR = 手順2でgit cloneした公開ディレクトリ
    7. 本スクリプトのパーミッションを755に設定。
    8. GitHub上のご自分のプロジェクトのWebhook設定画面を開き、以下のようにWebhookを追加。
      • Payload URL: http://example.com/github_webhook_updater.cgi (本スクリプトを設置したURL)
      • Content type: application/x-www-form-urlencoded
      • Secret: (空)
      • Which events would you like to trigger this webhook?: Just the push event.
    9. Test hookするか、masterにプッシュしてうまくいけば完了。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment