Created
March 17, 2016 12:41
-
-
Save pawitp/f589af10272606c13abf to your computer and use it in GitHub Desktop.
Poor man's CI with bitbucket
This file contains hidden or 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 | |
error_reporting(E_ALL | ~E_NOTICE); | |
// Config | |
$url = "https://bitbucket.org/USERNAME/PROJECT/get/master.zip"; | |
$user = "USERNAME"; | |
$pass = "PASSWORD"; | |
$tempfile = "thinkbox-ci.zip"; | |
$target = "./"; | |
$access_key = "ACCESS_KEY"; | |
// Helper | |
function rrmdir($dir) { | |
foreach (glob($dir . '/*') as $file) { | |
if (is_dir($file)) | |
rrmdir($file); | |
else | |
unlink($file); | |
} | |
rmdir($dir); | |
} | |
// Main code | |
header("Content-Type: text/plain"); | |
if ($_GET['key'] != $access_key) { | |
die("Invalid access key"); | |
} | |
if (file_exists($tempfile)) { | |
die("Temp file exists"); | |
} | |
// Download to tmp file | |
echo "download\n"; | |
$fh = fopen($tempfile, 'w'); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); | |
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass); | |
curl_setopt($ch, CURLOPT_FILE, $fh); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 30); | |
curl_exec($ch); | |
fclose($fh); | |
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
if ($status_code != 200) { | |
@unlink($tempfile); | |
die("Invalid response code: $status_code"); | |
} | |
echo "downloaded ".round((filesize($tempfile)/1024.0/1024.0), 3)." mb\n"; | |
// Extract zip | |
$zip = new ZipArchive; | |
$zip->open($tempfile); | |
$rootStat = $zip->statIndex(0); | |
// Write version | |
$version = substr($rootStat['name'], strrpos($rootStat['name'], '-') + 1, -1); | |
echo "version $version\n"; | |
file_put_contents("version.txt", $version); | |
for ($i = 1; $i < $zip->numFiles; $i++) { | |
$stat = $zip->statIndex($i); | |
// Strip name | |
$name = substr($stat['name'], strlen($rootStat['name'])); | |
if (substr($name, -1) == '/') { | |
// Directory | |
$tname = $target.$name; | |
if (substr_count($name, '/') == 1) { | |
// Initial directory | |
echo "clean $name\n"; | |
@rrmdir($tname); | |
} | |
echo "mkdir $name\n"; | |
mkdir($tname); | |
} else { | |
// Extract file | |
echo "extract $name\n"; | |
$fpIn = $zip->getStream($stat['name']); | |
$fpOut = fopen($target.$name, 'w'); | |
while ($data = fread($fpIn, 1024)) { | |
fwrite($fpOut, $data); | |
} | |
fclose($fpIn); | |
fclose($fpOut); | |
} | |
} | |
// Clean up | |
echo "cleanup\n"; | |
unlink($tempfile); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment