Skip to content

Instantly share code, notes, and snippets.

@hissy
Last active April 11, 2023 02:04
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hissy/6a114d0d9a85f3338aed to your computer and use it in GitHub Desktop.
Save hissy/6a114d0d9a85f3338aed to your computer and use it in GitHub Desktop.
Git Webhookを使ったCPIへのデプロイスクリプト
<?php
// CPIユーザーID(契約情報で確認してください)
$user_id = 'abc123defg';
// リポジトリ名(Backlogで確認してください)
$repo_name = 'repository_name';
// Gitレポジトリの位置の指定
$git_dir = '/usr/home/' . $user_id . '/' . $repo_name . '.git';
// 展開先ディレクトリの指定
$work_tree = '/usr/home/' . $user_id . '/html';
// logファイルの指定
$log_file = '/usr/home/' . $user_id . '/deploy.log';
// Gitコマンドパス
$git_command = '/usr/local/bin/git';
// リリースするブランチの指定
$deploy_ref = 'refs/heads/master';
/**
* Git Webフックを受信する
* BacklogのWebフックの仕様の解説はこちら
* http://www.backlog.jp/help/usersguide/git/userguide1710.html
*/
$payload = json_decode($_POST['payload']);
// 指定されたブランチかどうかの確認
$checkout = false;
if ($payload){
$ref = $payload->ref;
if ($ref == $deploy_ref) {
$checkout = true;
}
}
// 指定されたブランチの場合、fetch+checkoutを実行して、最終コミットをlogファイルに保存する
if ($checkout) {
exec($git_command . ' --git-dir=' . $git_dir . ' fetch');
exec($git_command . ' --git-dir=' . $git_dir . ' --work-tree=' . $work_tree . ' checkout -f');
$commit_hash = shell_exec($git_command . ' --git-dir=' . $git_dir . ' rev-parse --verify HEAD');
file_put_contents($log_file, date('r') . " Ref: " . $ref . " Commit: " . $commit_hash . "\n", FILE_APPEND);
}
<?php
// CPIユーザーID(契約情報で確認してください)
$user_id = 'abc123defg';
// リポジトリ名(Backlogで確認してください)
$repo_name = 'repository_name';
// Gitレポジトリの位置の指定
$git_dir = '/usr/home/' . $user_id . '/' . $repo_name . '.git';
// 展開先ディレクトリの指定
$work_tree = '/usr/home/' . $user_id . '/html';
// logファイルの指定
$log_file = '/usr/home/' . $user_id . '/deploy.log';
// Gitコマンドパス
$git_command = '/usr/local/bin/git';
// リリースするブランチの指定
$deploy_ref = 'refs/heads/master';
/**
* GitHub Webフックを受信する
*/
$payload = json_decode(file_get_contents('php://input'));
// 指定されたブランチかどうかの確認
$checkout = false;
if ($payload && isset($payload->ref)){
$ref = $payload->ref;
if ($ref == $deploy_ref) {
$checkout = true;
}
}
// 指定されたブランチの場合、fetch+checkoutを実行して、最終コミットをlogファイルに保存する
if ($checkout) {
exec($git_command . ' --git-dir=' . $git_dir . ' fetch');
exec($git_command . ' --git-dir=' . $git_dir . ' --work-tree=' . $work_tree . ' checkout -f');
$commit_hash = shell_exec($git_command . ' --git-dir=' . $git_dir . ' rev-parse --verify HEAD');
file_put_contents($log_file, date('r') . " Ref: " . $ref . " Commit: " . $commit_hash . "\n", FILE_APPEND);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment