Created
September 24, 2020 07:08
-
-
Save hemant-tivlabs/4b587de668be2be998e940a5a083e326 to your computer and use it in GitHub Desktop.
Helps deploy a Gitlab repo to the server location (includes clone and pull upon every commit to master branch)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* gitlab deploy webhook */ | |
define('GITLAB_VALIDATE_REQUEST_TOKEN', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); | |
define('GITLAB_PERSONAL_ACCESS_TOKEN', 'xxxxxxxxxxxxxxxxxxxx'); | |
define('GITLAB_USERNAME', 'xxxxxxxxxx'); | |
$repositories = array('xxxxxxxxxx'); | |
ob_start(); | |
try { | |
$request_headers = getallheaders(); | |
$json = file_get_contents('php://input'); | |
$request_data = json_decode($json, true); | |
$debug_file = './webhook-debug.log'; | |
if($f = fopen($debug_file, 'a')) { | |
fwrite($f, | |
'---------------------------------------------------'.PHP_EOL | |
.date('Y-m-d H:i:s').PHP_EOL | |
.print_r($request_headers, true).PHP_EOL | |
.print_r($request_data, true).PHP_EOL.PHP_EOL); | |
fclose($f); | |
} | |
if(isset($request_headers['X-Gitlab-Token']) | |
&& $request_headers['X-Gitlab-Token'] == constant('GITLAB_VALIDATE_REQUEST_TOKEN') | |
&& isset($request_data['repository']['name']) | |
&& in_array($request_data['repository']['name'], $repositories) | |
&& isset($request_data['ref']) | |
&& $request_data['ref'] == 'refs/heads/master') { | |
$repository_slug = $request_data['repository']['name']; | |
$repository_url = str_replace('https://', 'https://'.constant('GITLAB_USERNAME').':'.constant('GITLAB_PERSONAL_ACCESS_TOKEN').'@', $request_data['repository']['git_http_url']); | |
if(!is_dir('./'.$repository_slug)) { | |
exec('git clone '.$repository_url); | |
} else { | |
exec('cd '.getcwd().'/'.$repository_slug.' && git checkout master && git pull origin master >> '.getcwd().'/'.$repository_slug.'-deploy.log && echo "" >> '.getcwd().'/'.$repository_slug.'-deploy.log'); | |
} | |
} | |
} catch(Exception $e) { | |
echo 'ERROR: '.$e->getMessage(); | |
} | |
ob_get_clean(); | |
exit(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment