public function testAutoRollback() { // Setup $this->autoRollbackHelper(); $this->backupFile->buildFromDirectory($this->archivedDir); $this->backupFile->addEmptyDir("testDirectory"); $this->backupFile->compress(\Phar::GZ, '.tgz'); $newFile = $this->backupPath . '/' . uniqid() . '_code.tgz'; copy($this->backupFileName, $newFile); if (file_exists($this->backupFileName)) { unset($this->backupFile); unlink($this->backupFileName); } $gtzFile = str_replace('tar', 'tgz', $this->backupFileName); if (file_exists($gtzFile)) { unlink($gtzFile); } $this->backupFileName = $newFile; // Change the contents of a.txt $this->autoRollbackHelper(1); $this->assertEquals('foo changed', file_get_contents($this->archivedDir . 'a.txt')); $this->backupInfo->expects($this->once())->method('getBlacklist')->willReturn(['excluded']); // Rollback process $this->rollBack->execute($this->backupFileName); // Assert that the contents of a.txt has been restored properly $this->assertEquals('foo', file_get_contents($this->archivedDir . 'a.txt')); }
/** * @param string $project * @return array $return */ public function backupArchive($project) { // Exception if not defined if (!isset($this->config[$project]['archive'])) { throw new \Exception('No "Archive config" for this project', 1); } // Get backup settings $settings = $this->getArchiveSettings($project); // Get backup file prefix $backupFilePrefix = ''; if (!empty($settings['backup_file_prefix'])) { $backupFilePrefix = $settings['backup_file_prefix']; } // Set filename $filename = $backupFilePrefix . date('Ymd_His') . '.tar'; // Data required to backup Database $path = $this->getBackupPath($project, 'archive'); // Create Archive $phar = new \PharData($path . '/' . $filename); $phar->buildFromIterator(new \ArrayIterator($this->getArchiveFilesList($project))); // Compress and unlink none compress archive $phar->compress(\Phar::GZ); unlink($path . '/' . $filename); return $this->getBackupInfo($path, $filename); }
/** * @covers common\classes\AutoLoader::load_extension */ public function test_load_extension() { $extensions = glob(ROOT_PATH . DS . 'extensions' . DS . '*'); foreach ($extensions as $extension) { $name = ucwords(explode('.', basename($extension))[0]); self::assertTrue(AutoLoader::load_extension($name)); } self::assertFalse(AutoLoader::load_extension('NotExistedClass')); $name = 'fakeextension'; $extension_file = ROOT_PATH . DS . 'extensions' . DS . $name; $extension_build_dir = ROOT_PATH . DS . 'tests' . DS . 'resource' . DS . $name; $extension_file_tar = "{$extension_file}.tar"; $extension_file_gz = "{$extension_file}.tar.gz"; if (file_exists($extension_file_gz)) { Phar::unlinkArchive($extension_file_gz); } $phar = new PharData($extension_file_tar); $phar->buildFromDirectory($extension_build_dir); $phar->compress(Phar::GZ); if (file_exists($extension_file_tar)) { unlink($extension_file_tar); } self::assertTrue(AutoLoader::load_extension($name)); unlink($extension_file_gz); }
/** * {@inheritdoc} */ public function archive($sources, $target, $format, array $excludes = array()) { $sources = realpath($sources); // Phar would otherwise load the file which we don't want if (file_exists($target)) { unlink($target); } try { $filename = substr($target, 0, strrpos($target, $format) - 1); // Check if compress format if (isset(static::$compressFormats[$format])) { // Current compress format supported base on tar $target = $filename . '.tar'; } $phar = new \PharData($target, null, null, static::$formats[$format]); $files = new ArchivableFilesFinder($sources, $excludes); $phar->buildFromIterator($files, $sources); if (isset(static::$compressFormats[$format])) { // Check can be compressed? if (!$phar->canCompress(static::$compressFormats[$format])) { throw new \RuntimeException(sprintf('Can not compress to %s format', $format)); } // Delete old tar unlink($target); // Compress the new tar $phar->compress(static::$compressFormats[$format]); // Make the correct filename $target = $filename . '.' . $format; } return $target; } catch (\UnexpectedValueException $e) { $message = sprintf("Could not create archive '%s' from '%s': %s", $target, $sources, $e->getMessage()); throw new \RuntimeException($message, $e->getCode(), $e); } }
/** * Files constructor. * @param $target */ public function __construct($target) { $this->tarFilename = sys_get_temp_dir() . '/' . uniqid() . '.tar'; $phar = new \PharData($this->tarFilename); $phar->buildFromDirectory($target); $this->tarStream = fopen($this->tarFilename, 'r'); }
public static function copyDirToArchive($dir, $archive, $basename = null, $excludeDirs = null) { $dir = rtrim($dir, '/\\'); $basename = $basename ?: basename($dir); rex_dir::create(dirname($archive)); $files = array(); $iterator = rex_finder::factory($dir)->recursive()->filesOnly(); if ($excludeDirs) { $iterator->ignoreDirs($excludeDirs, false); } foreach ($iterator as $path => $file) { $subpath = str_replace($dir, $basename, $path); $subpath = str_replace('\\', '/', $subpath); $files[$subpath] = $path; } if (class_exists('ZipArchive')) { $zip = new ZipArchive(); $zip->open($archive, ZipArchive::CREATE); foreach ($files as $path => $realpath) { $zip->addFile($realpath, $path); } $zip->close(); } else { $phar = new PharData($archive, 0, null, Phar::ZIP); $phar->buildFromIterator(new ArrayIterator($files)); $phar->compressFiles(Phar::GZ); foreach ($files as $path => $realpath) { if (filesize($realpath) == 0) { $phar[$path]->decompress(); } } } }
/** * Load and extract our application development files * * @return void */ public static function extract() { /* Are we IN_DEV (and does it matter)? */ if (static::$checkInDev) { if (!defined('\\IPS\\IN_DEV') or !\IPS\IN_DEV) { return; } } /* Attempt to load our application */ $thisApp = NULL; $applications = \IPS\Application::applications(); foreach ($applications as $application) { if ($application->directory === static::$appDir) { $thisApp = $application; } } if (!$thisApp) { \IPS\Log::i(\LOG_ERR)->write('Error : Application ' . static::$appDir . ' not found', 'devpackager_error'); return; } /* Set our paths */ $appPath = join(\DIRECTORY_SEPARATOR, [\IPS\ROOT_PATH, 'applications', $thisApp->directory]); $devPath = join(\DIRECTORY_SEPARATOR, [$appPath, 'dev']); $devTar = join(\DIRECTORY_SEPARATOR, [$appPath, 'data', 'dev.tar']); /* Load and extract our tarball */ try { if (!is_dir($devPath)) { mkdir($devPath, 0777, true); } $devFiles = new \PharData($devTar, 0, NULL, \Phar::TAR); $devFiles->extractTo($devPath, NULL, TRUE); } catch (\Exception $e) { \IPS\Log::i(\LOG_ERR)->write('Error : ' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'devpackager_error'); } }
/** * Create package. */ public function create(array $args = array()) { $archBasename = $this->pkg->getSimpleName() . '-' . $this->pkg->getPrettyVersion(); /* Work around bug #67417 [NEW]: ::compress modifies archive basename creates temp file and rename it */ $tempName = getcwd() . '/pkl-tmp.tar'; if (file_exists($tempName)) { unlink($tempName); } $arch = new \PharData($tempName); $pkgDir = $this->pkg->getRootDir(); foreach ($this->pkg->getFiles() as $file) { if (is_file($file)) { $name = str_replace($pkgDir, '', $file); $arch->addFile($file, $name); } } if (file_exists($tempName)) { @unlink($tempName . '.gz'); } $arch->compress(\Phar::GZ); unset($arch); rename($tempName . '.gz', $archBasename . '.tgz'); unlink($tempName); if ($this->cb) { $cb = $this->cb; $cb($this->pkg); } }
public function action($parent) { $c = $parent->config; $util = new Utility(); if (strpos($_POST['path'], '/') === 0 || strpos($_POST['path'], '../') !== false || strpos($_POST['path'], './') === 0) { $this->r = array('wrong path', 400); return; } $path = $c['current_path'] . $_POST['path']; $info = pathinfo($path); $base_folder = $c['current_path'] . $util->fix_dirname($_POST['path']) . "/"; switch ($info['extension']) { case "zip": $zip = new \ZipArchive(); if ($zip->open($path) === true) { //make all the folders for ($i = 0; $i < $zip->numFiles; $i++) { $OnlyFileName = $zip->getNameIndex($i); $FullFileName = $zip->statIndex($i); if (substr($FullFileName['name'], -1, 1) == "/") { $util->create_folder($base_folder . $FullFileName['name']); } } //unzip into the folders for ($i = 0; $i < $zip->numFiles; $i++) { $OnlyFileName = $zip->getNameIndex($i); $FullFileName = $zip->statIndex($i); if (!(substr($FullFileName['name'], -1, 1) == "/")) { $fileinfo = pathinfo($OnlyFileName); if (in_array(strtolower($fileinfo['extension']), $ext)) { copy('zip://' . $path . '#' . $OnlyFileName, $base_folder . $FullFileName['name']); } } } $zip->close(); } else { $this->r = array('Could not extract. File might be corrupt.', 500); return; } break; case "gz": $p = new \PharData($path); $p->decompress(); // creates files.tar break; case "tar": // unarchive from the tar $phar = new \PharData($path); $phar->decompressFiles(); $files = array(); $util->check_files_extensions_on_phar($phar, $files, '', $ext); $phar->extractTo($current_path . fix_dirname($_POST['path']) . "/", $files, true); break; default: $this->r = array('This extension is not supported. Valid: zip, gz, tar.', 400); return; break; } }
static function gzipFolder($folder) { try { $a = new PharData($folder . '_archive.zip'); $a->buildFromDirectory($folder); } catch (Exception $e) { return false; } return true; }
/** * @param string $package path to package file */ function __construct($package, \Pyrus\Package $parent) { $package = realpath($package); if (!$package) { throw new Phar\Exception('Phar package ' . $package . ' does not exist'); } $pxml = false; $this->archive = $package; try { if (\Phar::isValidPharFilename($package, 1)) { $phar = new \Phar($package, \RecursiveDirectoryIterator::KEY_AS_FILENAME); $pxml = 'phar://' . $package . '/' . $phar->getMetaData(); } else { $phar = new \PharData($package, \RecursiveDirectoryIterator::KEY_AS_FILENAME); if ($phar->getMetaData()) { $pxml = 'phar://' . $package . '/' . $phar->getMetaData(); } } } catch (\Exception $e) { throw new Phar\Exception('Could not open Phar archive ' . $package, $e); } $package = str_replace('\\', '/', $package); try { if ($pxml === false) { $info = pathinfo($package); $internal = $info['filename']; if (isset($phar[$internal . '/.xmlregistry'])) { if ($phar instanceof \PharData) { $iterate = new \PharData('phar://' . $package . '/' . $internal . '/.xmlregistry'); } else { $iterate = new \Phar('phar://' . $package . '/' . $internal . '/.xmlregistry'); } foreach (new \RecursiveIteratorIterator($iterate, \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { $filename = $file->getFileName(); // default to new package.xml if (preg_match('@^(.+)\\-package.xml$@', $filename)) { $pxml = $file->getPathName(); break; } } } else { foreach (array('package2.xml', $internal . '/' . 'package2.xml', 'package.xml', $internal . '/' . 'package.xml') as $checkfile) { if (isset($phar[$checkfile])) { $this->_BCpackage = true; $pxml = $phar[$checkfile]->getPathName(); break; } } } } if ($pxml === false) { throw new Phar\Exception('No package.xml in archive'); } } catch (\Exception $e) { throw new Phar\Exception('Could not extract Phar archive ' . $package, $e); } parent::__construct(new \Pyrus\PackageFile($pxml, 'Pyrus\\PackageFile\\v2'), $parent); }
protected function getArchivers($use_cache = true) { $arcs = array('create' => array(), 'extract' => array()); $obj = $this; // php 5.3 compatibility if (class_exists('ZipArchive')) { $arcs['extract']['application/zip'] = array('cmd' => function ($archive, $path) use($obj) { $zip = new \ZipArchive(); if ($zip->open($archive)) { for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); if (empty($stat['size'])) { // directory continue; } $filename = $stat['name']; if (!$obj->tyghIsUTF8($filename) && function_exists('iconv')) { $newfile = iconv('cp866', 'utf-8', $filename); } else { $newfile = $filename; } $obj->tyghMkdir(dirname($path . '/' . $newfile)); copy('zip://' . $archive . '#' . $filename, $path . '/' . $newfile); } $zip->close(); return true; } return false; }, 'ext' => 'zip'); $arcs['create']['application/zip'] = array('cmd' => function ($archive, $files) use($obj) { $zip = new \ZipArchive(); if ($zip->open($archive, \ZipArchive::CREATE) === true) { $base_path = dirname($archive); foreach ($files as $file) { $path = $base_path . DIRECTORY_SEPARATOR . $file; if (is_file($path)) { $zip->addFile($path, $file); } elseif (is_dir($path)) { foreach ($obj->tyghGetFiles($path) as $_file) { $zip->addFile($path . DIRECTORY_SEPARATOR . $_file, $_file); } } } $zip->close(); return true; } return false; }, 'ext' => 'zip'); } if (class_exists('PharData')) { $arcs['extract']['application/x-gzip'] = array('cmd' => function ($archive, $path) { $phar = new \PharData($archive); $phar->extractTo($path, null, true); }, 'ext' => 'tgz'); } return $arcs; }
/** * Parse a tarball of .gcov files. **/ public function Parse($handle) { global $CDASH_BACKUP_DIRECTORY; // This function receives an open file handle, but we really just need // the path to this file so that we can extract it. $meta_data = stream_get_meta_data($handle); $filename = $meta_data["uri"]; fclose($handle); // Create a new directory where we can extract our tarball. $pathParts = pathinfo($filename); $dirName = $CDASH_BACKUP_DIRECTORY . "/" . $pathParts['filename']; mkdir($dirName); // Extract the tarball. $phar = new PharData($filename); $phar->extractTo($dirName); // Find the data.json file and extract the source directory from it. $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirName), RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $fileinfo) { if ($fileinfo->getFilename() == "data.json") { $jsonContents = file_get_contents($fileinfo->getRealPath()); $jsonDecoded = json_decode($jsonContents, true); if (is_null($jsonDecoded) || !array_key_exists("Source", $jsonDecoded) || !array_key_exists("Binary", $jsonDecoded)) { $this->DeleteDirectory($dirName); return false; } $this->SourceDirectory = $jsonDecoded['Source']; $this->BinaryDirectory = $jsonDecoded['Binary']; break; } } if (empty($this->SourceDirectory) || empty($this->BinaryDirectory)) { $this->DeleteDirectory($dirName); return false; } // Check if any Labels.json files were included $iterator->rewind(); foreach ($iterator as $fileinfo) { if ($fileinfo->getFilename() == "Labels.json") { $this->ParseLabelsFile($fileinfo); } } // Recursively search for .gcov files and parse them. $iterator->rewind(); foreach ($iterator as $fileinfo) { if (pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION) == "gcov") { $this->ParseGcovFile($fileinfo); } } // Insert coverage summary (removing any old results first) //$this->CoverageSummary->RemoveAll(); $this->CoverageSummary->Insert(); $this->CoverageSummary->ComputeDifference(); // Delete the directory when we're done. $this->DeleteDirectory($dirName); return true; }
public function imgCreate($tag, $dkFileData) { file_put_contents('Dockerfile', $dkFileData); $dkfiletar = new PharData('Dockerfile.tar'); $dkfiletar->addFile('Dockerfile'); //执行此行代码后生成Dockerfile.tar.gz文件 $dkfiletar->compress(Phar::GZ); $this->cmObj->curlPostFile(DOCKER_URL . '/build?t=' . $tag . '&nocache=1', 'Dockerfile.tar.gz', array('Content-Type:application/tar')); return $this->cmObj->curlHttpCode(); }
/** * TODO: Is it possible to extract directly from the stream? With stream filters? * * @param $target */ public function extract($target) { if (!isset($this->target)) { $this->target = sys_get_temp_dir() . '/' . uniqid() . '.tar'; $this->saveTar($this->target); $this->removeTarget = true; } $phar = new \PharData($this->target); $phar->extractTo($target); }
/** * Загружает и распаковывает данные с ipgeobase.ru * * @param string $path Путь до каталога с БД * @return boolean */ public function loadArchive($path) { $path = rtrim($path, '/'); $tmpfname = '/tmp/' . basename($this->archiveUri); copy($this->archiveUri, $tmpfname); $phar = new \PharData($tmpfname); $phar->extractTo($path, null, true); $cities = file_get_contents($path . '/cities.txt'); file_put_contents($path . '/cities.txt', iconv('WINDOWS-1251', 'UTF-8', $cities)); return true; }
public function extract($source, $target) { try { $phar = new PharData($source); $phar->extractTo($target, null, true); // throws exception exec("find " . $target . " -type d -exec chmod 0777 {} +"); exec("find " . $target . " -type f -exec chmod 0777 {} +"); } catch (Exception $e) { } }
/** * @param string $folder * * @return bool */ protected function backupFolder($folder) { GeneralUtility::mkdir_deep($this->backupPath); $compressedFileName = $folder . '_' . time() . '.tar'; $phar = new \PharData($this->backupPath . $compressedFileName); if ($phar->buildFromDirectory(PATH_site . $folder, '/^(?!_temp_|_processed_|_recycler_).*/')) { BackupUtility::generateBackupLog($folder, $compressedFileName . '.gz', $this->backupPath, $this->backupsToKeep); BackupUtility::gzCompressFile($this->backupPath . $compressedFileName); return true; } return false; }
public function extract() { $varDir = $this->rootDir . DIRECTORY_SEPARATOR . 'var'; $tarFile = $varDir . DIRECTORY_SEPARATOR . 'magento.tar'; if (file_exists($tarFile)) { unlink($tarFile); } $phar = new \PharData($this->filename); $phar->decompress(); $phar = new \PharData($tarFile); $phar->extractTo($varDir, null, true); }
function run_with_iterator(Iterator $it, $root = '') { $tmpnam = tempnam('/tmp', 'testzip'); unlink($tmpnam); $tmpnam .= '.zip'; $pd = new PharData($tmpnam); var_dump($pd->buildFromIterator($it, $root)); $z = zip_open($tmpnam); while ($entry = zip_read($z)) { var_dump([zip_entry_name($entry), zip_entry_filesize($entry)]); } }
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { parent::execute($input, $output); $language = $input->getArgument('language'); $tmpFolder = $input->getOption('tmp'); $_configuration = $this->getHelper('configuration')->getConfiguration(); $connection = $this->getHelper('configuration')->getConnection(); if ($connection) { $lang = isset($language) ? $language : null; $lang = mysql_real_escape_string($lang); $q = mysql_query("SELECT * FROM language WHERE english_name = '{$lang}' "); $langInfo = mysql_fetch_array($q, MYSQL_ASSOC); if (!$langInfo) { $output->writeln("<comment>Language '{$lang}' is not registered in the Chamilo Database</comment>"); $q = mysql_query("SELECT * FROM language WHERE parent_id IS NULL or parent_id = 0"); $output->writeln("<comment>Available languages are: </comment>"); while ($langRow = mysql_fetch_array($q, MYSQL_ASSOC)) { $output->write($langRow['english_name'] . ", "); } $output->writeln(' '); $q = mysql_query("SELECT * FROM language WHERE parent_id <> 0"); $output->writeln("<comment>Available sub languages are: </comment>"); while ($langRow = mysql_fetch_array($q, MYSQL_ASSOC)) { $output->write($langRow['english_name'] . ", "); } $output->writeln(' '); exit; } else { $output->writeln("<comment>Language</comment> <info>'{$lang}'</info> <comment>is registered in the Chamilo installation with iso code: </comment><info>{$langInfo['isocode']} </info>"); } $langFolder = $_configuration['root_sys'] . 'main/lang/' . $lang; if (!is_dir($langFolder)) { $output->writeln("<comment>Language '{$lang}' does not exist in the path: {$langFolder}</comment>"); } if (empty($tmpFolder)) { $tmpFolder = '/tmp/'; $output->writeln("<comment>No temporary directory defined. Assuming /tmp/. Please make sure you have *enough space* left on that device"); } if (!is_dir($tmpFolder)) { $output->writeln("<comment>Temporary directory: {$tmpFolder} is not a valid dir path, using /tmp/ </comment>"); $tmpFolder = '/tmp/'; } if ($langInfo) { $output->writeln("<comment>Creating translation package</comment>"); $fileName = $tmpFolder . $langInfo['english_name'] . '.tar'; $phar = new \PharData($fileName); $phar->buildFromDirectory($langFolder); $phar->setMetadata($langInfo); $output->writeln("<comment>File created:</comment> <info>{$fileName}</info>"); } } }
/** * @param \SplFileInfo $archive * * @return bool * @throws \Exception */ public function extract(\SplFileInfo $archive, \SplFileInfo $destination) { if (preg_match('/^win/i', PHP_OS)) { $targz = new \PharData($archive->getPathname()); /** @var \PharData $tar */ $tar = $targz->decompress(); $tar->extractTo($destination->getPathname()); unlink(str_replace('.tar.gz', '.tar', $archive->getPathname())); } else { exec('tar xzf ' . $archive->getPathname() . ' -C ' . $destination->getPathname()); } return true; }
private static function _extract($tarball, $dest) { if (!class_exists('PharData')) { $cmd = "tar xz --strip-components=1 --directory=%s -f {$tarball}"; WP_CLI::launch(Utils\esc_cmd($cmd, $dest)); return; } $phar = new PharData($tarball); $tempdir = implode(DIRECTORY_SEPARATOR, array(dirname($tarball), basename($tarball, '.tar.gz'), $phar->getFileName())); $phar->extractTo(dirname($tempdir), null, true); self::_copy_overwrite_files($tempdir, $dest); self::_rmdir(dirname($tempdir)); }
/** * Create tgz archive. */ public function compress() { $tarFile = $this->rootDir . '/' . $this->tmpName . '.tar'; $tgzFile = $this->rootDir . '/' . $this->tmpName . '.tgz'; $phar = new \PharData($tarFile); foreach ($this->files as $file) { $phar->addFile($file[0], $file[1]); } // Compress .tar file to .tgz $phar->compress(\Phar::GZ, '.tgz'); rename($tgzFile, $this->rootDir . '/' . $this->name); // Both files (.tar and .tgz) exist. Remove the temporary .tar archive unlink($tarFile); }
protected function retrieveAndPrintHtml($suite) { $tempFile = str_replace('.', '', tempnam(sys_get_temp_dir(), 'C3')) . '.tar'; file_put_contents($tempFile, $this->c3Request('html')); $destDir = Configuration::outputDir() . $suite . '.remote.coverage'; if (is_dir($destDir)) { FileSystem::doEmptyDir($destDir); } else { mkdir($destDir, 0777, true); } $phar = new \PharData($tempFile); $phar->extractTo($destDir); unlink($tempFile); }
/** * Installs PEAR source files according to package.xml definitions and removes extracted files * * @param string $target target install location. all source installation would be performed relative to target path. * @param array $roles types of files to install. default role for PEAR source files are 'php'. * @param array $vars used for replacement tasks * @throws \RuntimeException * @throws \UnexpectedValueException * */ public function extractTo($target, array $roles = array('php' => '/', 'script' => '/bin'), $vars = array()) { $extractionPath = $target . '/tarball'; try { $archive = new \PharData($this->file); $archive->extractTo($extractionPath, null, true); if (!is_file($this->combine($extractionPath, '/package.xml'))) { throw new \RuntimeException('Invalid PEAR package. It must contain package.xml file.'); } $fileCopyActions = $this->buildCopyActions($extractionPath, $roles, $vars); $this->copyFiles($fileCopyActions, $extractionPath, $target, $roles, $vars); $this->filesystem->removeDirectory($extractionPath); } catch (\Exception $exception) { throw new \UnexpectedValueException(sprintf('Failed to extract PEAR package %s to %s. Reason: %s', $this->file, $target, $exception->getMessage()), 0, $exception); } }
public function archive($sources, $target, $format, array $excludes = array()) { $sources = realpath($sources); if (file_exists($target)) { unlink($target); } try { $phar = new \PharData($target, null, null, static::$formats[$format]); $files = new ArchivableFilesFinder($sources, $excludes); $phar->buildFromIterator($files, $sources); return $target; } catch (\UnexpectedValueException $e) { $message = sprintf("Could not create archive '%s' from '%s': %s", $target, $sources, $e->getMessage()); throw new \RuntimeException($message, $e->getCode(), $e); } }
public function create($execution, $format, $hrefs) { $this->dirs = array(); $this->files = array(); $this->sc401 = false; $this->add_hrefs($hrefs); if ($this->sc401) { return 401; } else { if (count($this->dirs) === 0 && count($this->files) === 0) { return 404; } } $target = H5ai::normalize_path(sys_get_temp_dir(), true) . "h5ai-selection-" . microtime(true) . rand() . "." . $format; try { if ($execution === "shell") { if ($format === "tar") { $cmd = Archive::$TAR_CMD; } else { if ($format === "zip") { $cmd = Archive::$ZIP_CMD; } else { return null; } } $cmd = str_replace("[ROOTDIR]", "\"" . $this->h5ai->getRootAbsPath() . "\"", $cmd); $cmd = str_replace("[TARGET]", "\"" . $target . "\"", $cmd); $cmd = str_replace("[DIRS]", count($this->dirs) ? "\"" . implode("\" \"", array_values($this->dirs)) . "\"" : "", $cmd); $cmd = str_replace("[FILES]", count($this->files) ? "\"" . implode("\" \"", array_values($this->files)) . "\"" : "", $cmd); `{$cmd}`; } else { if ($execution === "php") { $archive = new PharData($target); foreach ($this->dirs as $archivedDir) { $archive->addEmptyDir($archivedDir); } foreach ($this->files as $realFile => $archivedFile) { $archive->addFile($realFile, $archivedFile); // very, very slow :/ } } } } catch (Exeption $err) { return 500; } return @filesize($target) ? $target : null; }
/** * Parse a tarball of JSON files. **/ public function Parse($handle) { global $CDASH_BACKUP_DIRECTORY; // This function receives an open file handle, but we really just need // the path to this file so that we can extract it. $meta_data = stream_get_meta_data($handle); $filename = $meta_data["uri"]; fclose($handle); // Create a new directory where we can extract our tarball. $pathParts = pathinfo($filename); $dirName = $CDASH_BACKUP_DIRECTORY . "/" . $pathParts['filename']; mkdir($dirName); // Extract the tarball. $phar = new PharData($filename); $phar->extractTo($dirName); // Check if this submission included a package_map.json file. // This tells us how Java packages correspond to CDash subprojects. $mapFound = false; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirName), RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $fileinfo) { if ($fileinfo->getFilename() == "package_map.json") { $this->ParsePackageMap($fileinfo); } } // Recursively search for .java.json files and parse them. $iterator->rewind(); foreach ($iterator as $fileinfo) { // need the longest extension, so getExtension() won't do here. $ext = substr(strstr($fileinfo->getFilename(), '.'), 1); if ($ext === "java.json") { $this->ParseJavaJSONFile($fileinfo); } } // Insert coverage summaries $completedSummaries = array(); foreach ($this->CoverageSummaries as $coverageSummary) { if (in_array($coverageSummary->BuildId, $completedSummaries)) { continue; } $coverageSummary->Insert(); $coverageSummary->ComputeDifference(); $completedSummaries[] = $coverageSummary->BuildId; } // Delete the directory when we're done. $this->DeleteDirectory($dirName); return true; }
/** * @inheritDoc */ public function extractTo($dir) { $phar = new \PharData($this->file); $result = $phar->extractTo($dir, null, true); $phar = null; return $result; }