/** * Builds the archives of the repository. * * @param array $packages List of packages to dump */ public function dump(array $packages) { $helper = new ArchiveBuilderHelper($this->output, $this->config['archive']); $directory = $helper->getDirectory($this->outputDir); $this->output->writeln(sprintf("<info>Creating local downloads in '%s'</info>", $directory)); $format = isset($this->config['archive']['format']) ? $this->config['archive']['format'] : 'zip'; $endpoint = isset($this->config['archive']['prefix-url']) ? $this->config['archive']['prefix-url'] : $this->config['homepage']; $includeArchiveChecksum = isset($this->config['archive']['checksum']) ? (bool) $this->config['archive']['checksum'] : true; $composerConfig = Factory::createConfig(); $factory = new Factory(); $io = new ConsoleIO($this->input, $this->output, $this->helperSet); $io->loadConfiguration($composerConfig); /* @var \Composer\Downloader\DownloadManager $downloadManager */ $downloadManager = $factory->createDownloadManager($io, $composerConfig); /* @var \Composer\Package\Archiver\ArchiveManager $archiveManager */ $archiveManager = $factory->createArchiveManager($composerConfig, $downloadManager); $archiveManager->setOverwriteFiles(false); shuffle($packages); /* @var \Composer\Package\CompletePackage $package */ foreach ($packages as $package) { if ($helper->isSkippable($package)) { continue; } $this->output->writeln(sprintf("<info>Dumping '%s'.</info>", $package->getName())); try { if ('pear-library' === $package->getType()) { // PEAR packages are archives already $filesystem = new Filesystem(); $packageName = $archiveManager->getPackageFilename($package); $path = realpath($directory) . '/' . $packageName . '.' . pathinfo($package->getDistUrl(), PATHINFO_EXTENSION); if (!file_exists($path)) { $downloadDir = sys_get_temp_dir() . '/composer_archiver/' . $packageName; $filesystem->ensureDirectoryExists($downloadDir); $downloadManager->download($package, $downloadDir, false); $filesystem->ensureDirectoryExists($directory); $filesystem->rename($downloadDir . '/' . pathinfo($package->getDistUrl(), PATHINFO_BASENAME), $path); $filesystem->removeDirectory($downloadDir); } // Set archive format to `file` to tell composer to download it as is $archiveFormat = 'file'; } else { $path = $archiveManager->archive($package, $format, $directory); $archiveFormat = $format; } $archive = basename($path); $distUrl = sprintf('%s/%s/%s', $endpoint, $this->config['archive']['directory'], $archive); $package->setDistType($archiveFormat); $package->setDistUrl($distUrl); if ($includeArchiveChecksum) { $package->setDistSha1Checksum(hash_file('sha1', $path)); } $package->setDistReference($package->getSourceReference()); } catch (\Exception $exception) { if (!$this->skipErrors) { throw $exception; } $this->output->writeln(sprintf("<error>Skipping Exception '%s'.</error>", $exception->getMessage())); } } }
/** * {@inheritdoc} */ public function archive($sources, $target, $format, array $excludes = array()) { $fs = new Filesystem(); $sources = $fs->normalizePath($sources); $zip = new ZipArchive(); $res = $zip->open($target, ZipArchive::CREATE); if ($res === true) { $files = new ArchivableFilesFinder($sources, $excludes); foreach ($files as $file) { /** @var $file \SplFileInfo */ $filepath = strtr($file->getPath() . "/" . $file->getFilename(), '\\', '/'); $localname = str_replace($sources . '/', '', $filepath); if ($file->isDir()) { $zip->addEmptyDir($localname); } else { $zip->addFile($filepath, $localname); } } if ($zip->close()) { return $target; } } $message = sprintf("Could not create archive '%s' from '%s': %s", $target, $sources, $zip->getStatusString()); throw new \RuntimeException($message); }
/** * {@inheritDoc} */ public function initialize() { if (static::isLocalUrl($this->url)) { $this->repoDir = str_replace('file://', '', $this->url); } else { $this->repoDir = $this->config->get('home') . '/cache.git/' . preg_replace('{[^a-z0-9.]}i', '-', $this->url) . '/'; // update the repo if it is a valid git repository if (is_dir($this->repoDir) && 0 === $this->process->execute('git remote', $output, $this->repoDir)) { if (0 !== $this->process->execute('git remote update --prune origin', $output, $this->repoDir)) { $this->io->write('<error>Failed to update ' . $this->url . ', package information from this repository may be outdated (' . $this->process->getErrorOutput() . ')</error>'); } } else { // clean up directory and do a fresh clone into it $fs = new Filesystem(); $fs->removeDirectory($this->repoDir); // added in git 1.7.1, prevents prompting the user putenv('GIT_ASKPASS=echo'); $command = sprintf('git clone --mirror %s %s', escapeshellarg($this->url), escapeshellarg($this->repoDir)); if (0 !== $this->process->execute($command, $output)) { $output = $this->process->getErrorOutput(); if (0 !== $this->process->execute('git --version', $ignoredOutput)) { throw new \RuntimeException('Failed to clone ' . $this->url . ', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()); } throw new \RuntimeException('Failed to clone ' . $this->url . ', could not read packages from it' . "\n\n" . $output); } } } $this->getTags(); $this->getBranches(); }
/** * Makes sure the given directory exists and has no content. * * @param string $directory */ protected function ensureDirectoryExistsAndClear($directory) { if (is_dir($directory)) { $this->fs->removeDirectory($directory); } mkdir($directory, 0777, true); }
/** * @dataProvider getTestFiles */ public function testIntegration(\SplFileInfo $testFile) { $testData = $this->parseTestFile($testFile); $cmd = 'php ' . __DIR__ . '/../../../bin/composer --no-ansi ' . $testData['RUN']; $proc = new Process($cmd); $exitcode = $proc->run(); if (isset($testData['EXPECT'])) { $this->assertEquals($testData['EXPECT'], $this->cleanOutput($proc->getOutput()), 'Error Output: ' . $proc->getErrorOutput()); } if (isset($testData['EXPECT-REGEX'])) { $this->assertRegExp($testData['EXPECT-REGEX'], $this->cleanOutput($proc->getOutput()), 'Error Output: ' . $proc->getErrorOutput()); } if (isset($testData['EXPECT-ERROR'])) { $this->assertEquals($testData['EXPECT-ERROR'], $this->cleanOutput($proc->getErrorOutput())); } if (isset($testData['EXPECT-ERROR-REGEX'])) { $this->assertRegExp($testData['EXPECT-ERROR-REGEX'], $this->cleanOutput($proc->getErrorOutput())); } if (isset($testData['EXPECT-EXIT-CODE'])) { $this->assertSame($testData['EXPECT-EXIT-CODE'], $exitcode); } // Clean up. $fs = new Filesystem(); if (isset($testData['test_dir']) && is_dir($testData['test_dir'])) { $fs->removeDirectory($testData['test_dir']); } }
public function testBuildPhar() { if (defined('HHVM_VERSION')) { $this->markTestSkipped('Building the phar does not work on HHVM.'); } $target = dirname(self::$pharPath); $fs = new Filesystem(); $fs->removeDirectory($target); $fs->ensureDirectoryExists($target); chdir($target); $it = new \RecursiveDirectoryIterator(__DIR__ . '/../../../', \RecursiveDirectoryIterator::SKIP_DOTS); $ri = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::SELF_FIRST); foreach ($ri as $file) { $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName(); if ($file->isDir()) { $fs->ensureDirectoryExists($targetPath); } else { copy($file->getPathname(), $targetPath); } } $proc = new Process('php ' . escapeshellarg('./bin/compile'), $target); $exitcode = $proc->run(); if ($exitcode !== 0 || trim($proc->getOutput())) { $this->fail($proc->getOutput()); } $this->assertTrue(file_exists(self::$pharPath)); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $filesystem = new Filesystem(); $packageName = $this->getPackageFilename($name = $this->argument('name')); if (!($targetDir = $this->option('dir'))) { $targetDir = $this->container->path(); } $sourcePath = $this->container->get('path.packages') . '/' . $name; $filesystem->ensureDirectoryExists($targetDir); $target = realpath($targetDir) . '/' . $packageName . '.zip'; $filesystem->ensureDirectoryExists(dirname($target)); $exludes = []; if (file_exists($composerJsonPath = $sourcePath . '/composer.json')) { $jsonFile = new JsonFile($composerJsonPath); $jsonData = $jsonFile->read(); if (!empty($jsonData['archive']['exclude'])) { $exludes = $jsonData['archive']['exclude']; } if (!empty($jsonData['archive']['scripts'])) { system($jsonData['archive']['scripts'], $return); if ($return !== 0) { throw new \RuntimeException('Can not executes scripts.'); } } } $tempTarget = sys_get_temp_dir() . '/composer_archive' . uniqid() . '.zip'; $filesystem->ensureDirectoryExists(dirname($tempTarget)); $archiver = new PharArchiver(); $archivePath = $archiver->archive($sourcePath, $tempTarget, 'zip', $exludes); rename($archivePath, $target); $filesystem->remove($tempTarget); return $target; }
private function normalize(string $path) : string { if (!$this->filesystem->isAbsolutePath($path)) { $path = $this->basePath . '/' . $path; } return $this->filesystem->normalizePath($path); }
public function tearDown() { if (is_dir($this->tmpdir)) { $fs = new Filesystem(); $fs->removeDirectory($this->tmpdir); } }
protected function tearDown() { if (is_dir($this->root)) { $fs = new Filesystem(); $fs->removeDirectory($this->root); } }
/** * Duplicates search packages * * @param string $templatePath * @param array $vars */ protected function checkDuplicates($templatePath, array $vars = array()) { /** * Incorrect paths for backward compatibility */ $oldLocations = array('module' => 'local/modules/{$name}/', 'component' => 'local/components/{$name}/', 'theme' => 'local/templates/{$name}/'); $packageType = substr($vars['type'], strlen('bitrix') + 1); $oldLocation = str_replace('{$name}', $vars['name'], $oldLocations[$packageType]); if (in_array($oldLocation, static::$checkedDuplicates)) { return; } if ($oldLocation !== $templatePath && file_exists($oldLocation) && $this->io && $this->io->isInteractive()) { $this->io->writeError(' <error>Duplication of packages:</error>'); $this->io->writeError(' <info>Package ' . $oldLocation . ' will be called instead package ' . $templatePath . '</info>'); while (true) { switch ($this->io->ask(' <info>Delete ' . $oldLocation . ' [y,n,?]?</info> ', '?')) { case 'y': $fs = new Filesystem(); $fs->removeDirectory($oldLocation); break 2; case 'n': break 2; case '?': default: $this->io->writeError([' y - delete package ' . $oldLocation . ' and to continue with the installation', ' n - don\'t delete and to continue with the installation']); $this->io->writeError(' ? - print help'); break; } } } static::$checkedDuplicates[] = $oldLocation; }
protected function tearDown() { parent::tearDown(); $fs = new Filesystem(); $fs->remove($this::TEST_PATH); }
/** * {@inheritDoc} */ public function initialize() { if (static::isLocalUrl($this->url)) { $this->repoDir = str_replace('file://', '', $this->url); } else { $this->repoDir = sys_get_temp_dir() . '/composer-' . preg_replace('{[^a-z0-9.]}i', '-', $this->url) . '/'; // update the repo if it is a valid git repository if (is_dir($this->repoDir) && 0 === $this->process->execute('git remote', $output, $this->repoDir)) { $this->process->execute('git remote update --prune origin', $output, $this->repoDir); } else { // clean up directory and do a fresh clone into it $fs = new Filesystem(); $fs->removeDirectory($this->repoDir); $command = sprintf('git clone --mirror %s %s', escapeshellarg($this->url), escapeshellarg($this->repoDir)); if (0 !== $this->process->execute($command, $output)) { $output = $this->process->getErrorOutput(); if (0 !== $this->process->execute('git --version', $ignoredOutput)) { throw new \RuntimeException('Failed to clone ' . $this->url . ', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()); } throw new \RuntimeException('Failed to clone ' . $this->url . ', could not read packages from it' . "\n\n" . $output); } } } $this->getTags(); $this->getBranches(); }
/** * Duplicates search packages. * * @param string $path * @param array $vars */ protected function checkDuplicates($path, array $vars = array()) { $packageType = substr($vars['type'], strlen('bitrix') + 1); $localDir = explode('/', $vars['bitrix_dir']); array_pop($localDir); $localDir[] = 'local'; $localDir = implode('/', $localDir); $oldPath = str_replace(array('{$bitrix_dir}', '{$name}'), array($localDir, $vars['name']), $this->locations[$packageType]); if (in_array($oldPath, static::$checkedDuplicates)) { return; } if ($oldPath !== $path && file_exists($oldPath) && $this->io && $this->io->isInteractive()) { $this->io->writeError(' <error>Duplication of packages:</error>'); $this->io->writeError(' <info>Package ' . $oldPath . ' will be called instead package ' . $path . '</info>'); while (true) { switch ($this->io->ask(' <info>Delete ' . $oldPath . ' [y,n,?]?</info> ', '?')) { case 'y': $fs = new Filesystem(); $fs->removeDirectory($oldPath); break 2; case 'n': break 2; case '?': default: $this->io->writeError(array(' y - delete package ' . $oldPath . ' and to continue with the installation', ' n - don\'t delete and to continue with the installation')); $this->io->writeError(' ? - print help'); break; } } } static::$checkedDuplicates[] = $oldPath; }
/** * {@inheritDoc} */ public function initialize() { if (static::isLocalUrl($this->url)) { $this->repoDir = str_replace('file://', '', $this->url); } else { $cacheDir = $this->config->get('cache-vcs-dir'); $this->repoDir = $cacheDir . '/' . preg_replace('{[^a-z0-9]}i', '-', $this->url) . '/'; $fs = new Filesystem(); $fs->ensureDirectoryExists($cacheDir); if (!is_writable(dirname($this->repoDir))) { throw new \RuntimeException('Can not clone ' . $this->url . ' to access package information. The "' . $cacheDir . '" directory is not writable by the current user.'); } // update the repo if it is a valid hg repository if (is_dir($this->repoDir) && 0 === $this->process->execute('hg summary', $output, $this->repoDir)) { if (0 !== $this->process->execute('hg pull -u', $output, $this->repoDir)) { $this->io->write('<error>Failed to update ' . $this->url . ', package information from this repository may be outdated (' . $this->process->getErrorOutput() . ')</error>'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->repoDir); if (0 !== $this->process->execute(sprintf('hg clone %s %s', escapeshellarg($this->url), escapeshellarg($this->repoDir)), $output, $cacheDir)) { $output = $this->process->getErrorOutput(); if (0 !== $this->process->execute('hg --version', $ignoredOutput)) { throw new \RuntimeException('Failed to clone ' . $this->url . ', hg was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()); } throw new \RuntimeException('Failed to clone ' . $this->url . ', could not read packages from it' . "\n\n" . $output); } } } $this->getTags(); $this->getBranches(); }
/** * Get the target path for a rendered file from a template file. * * @since 0.1.0 * * @param string $pathname The path and file name to the template file. * * @return string The target path and file name to use for the rendered file. */ protected function getTargetPath($pathname) { $filesystem = new Filesystem(); $templatesFolder = $this->getConfigKey('Folders', 'templates'); $folderDiff = '/' . $filesystem->findShortestPath(SetupHelper::getRootFolder(), $templatesFolder); return (string) $this->removeTemplateExtension(str_replace($folderDiff, '', $pathname)); }
/** * Runs the project configurator. * * @return void */ public function run() { $namespace = $this->ask('Namespace', function ($namespace) { return $this->validateNamespace($namespace); }, 'App'); $packageName = $this->ask('Package name', function ($packageName) { return $this->validatePackageName($packageName); }, $this->suggestPackageName($namespace)); $license = $this->ask('License', function ($license) { return trim($license); }, 'proprietary'); $description = $this->ask('Description', function ($description) { return trim($description); }, ''); $file = new JsonFile('./composer.json'); $config = $file->read(); $config['name'] = $packageName; $config['license'] = $license; $config['description'] = $description; $config['autoload']['psr-4'] = [$namespace . '\\' => 'src/']; $config['autoload-dev']['psr-4'] = [$namespace . '\\Tests\\' => 'tests/']; unset($config['scripts']['post-root-package-install']); $config['extra']['branch-alias']['dev-master'] = '1.0-dev'; $file->write($config); $this->composer->setPackage(Factory::create($this->io, null, true)->getPackage()); // reload root package $filesystem = new Filesystem(); $filesystem->removeDirectory('./app/Distribution'); }
protected function ensureDirectoryExistsAndClear($directory) { $fs = new Filesystem(); if (is_dir($directory)) { $fs->removeDirectory($directory); } mkdir($directory, 0777, true); }
protected function tearDown() { $this->plugin = null; $this->composer = null; $this->io = null; $fs = new Filesystem(); $fs->remove(sys_get_temp_dir() . '/composer-test-repo-cache'); }
protected function tearDown() { $fs = new Filesystem(); $dirs = glob(__DIR__ . '/../_fixtures/*/*/vendor'); foreach ($dirs as $dir) { $fs->removeDirectoryPhp($dir); } }
public function tearDown() { chdir($this->prevCwd); if (is_dir($this->tempComposerHome)) { $fs = new Filesystem(); $fs->removeDirectory($this->tempComposerHome); } }
protected function execute(InputInterface $input, OutputInterface $output) { $baseUrl = (extension_loaded('openssl') ? 'https' : 'http') . '://' . self::HOMEPAGE; $remoteFilesystem = new RemoteFilesystem($this->getIO()); $config = Factory::createConfig(); $cacheDir = $config->get('cache-dir'); $rollbackDir = $config->get('home'); $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir; if (!is_writable($tmpDir)) { throw new FilesystemException('Composer update failed: the "' . $tmpDir . '" directory used to download the temp file could not be written'); } if (!is_writable($localFilename)) { throw new FilesystemException('Composer update failed: the "' . $localFilename . '" file could not be written'); } if ($input->getOption('rollback')) { return $this->rollback($output, $rollbackDir, $localFilename); } $latestVersion = trim($remoteFilesystem->getContents(self::HOMEPAGE, $baseUrl . '/version', false)); $updateVersion = $input->getArgument('version') ?: $latestVersion; if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) { $output->writeln('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>'); return 1; } if (Composer::VERSION === $updateVersion) { $output->writeln('<info>You are already using composer version ' . $updateVersion . '.</info>'); return 0; } $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar') . '-temp.phar'; $backupFile = sprintf('%s/%s-%s%s', $rollbackDir, strtr(Composer::RELEASE_DATE, ' :', '_-'), preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION), self::OLD_INSTALL_EXT); $output->writeln(sprintf("Updating to version <info>%s</info>.", $updateVersion)); $remoteFilename = $baseUrl . (preg_match('{^[0-9a-f]{40}$}', $updateVersion) ? '/composer.phar' : "/download/{$updateVersion}/composer.phar"); $remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename); if (!file_exists($tempFilename)) { $output->writeln('<error>The download of the new composer version failed for an unexpected reason</error>'); return 1; } if ($input->getOption('clean-backups')) { $files = $this->getOldInstallationFiles($rollbackDir); if (!empty($files)) { $fs = new Filesystem(); foreach ($files as $file) { $output->writeln('<info>Removing: ' . $file . '</info>'); $fs->remove($file); } } } if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) { $output->writeln('<error>The file is corrupted (' . $err->getMessage() . ').</error>'); $output->writeln('<error>Please re-run the self-update command to try again.</error>'); return 1; } if (file_exists($backupFile)) { $output->writeln('Use <info>composer self-update --rollback</info> to return to version ' . Composer::VERSION); } else { $output->writeln('<warning>A backup of the current version could not be written to ' . $backupFile . ', no rollback possible</warning>'); } }
/** * Constructs the include file content * * @return string * @throws \RuntimeException * @throws \InvalidArgumentException */ protected function getIncludeFileContent() { $includeFileTemplate = $this->filesystem->normalizePath(__DIR__ . '/../' . self::RESOURCES_PATH . '/' . self::INCLUDE_FILE_TEMPLATE); $includeFileContent = file_get_contents($includeFileTemplate); foreach ($this->tokens as $token) { $includeFileContent = self::replaceToken($token->getName(), $token->getContent(), $includeFileContent); } return $includeFileContent; }
public function getClassmap() : \Traversable { $filesystem = new Filesystem(); $vendorPath = $filesystem->normalizePath(realpath($this->config->get('vendor-dir'))); $classmapPath = $vendorPath . '/composer/autoload_classmap.php'; if (!is_file($classmapPath)) { throw new \RuntimeException('Th dumped classmap does not exists. Try to run `composer dump-autoload --optimize` first.'); } yield from (include $vendorPath . '/composer/autoload_classmap.php'); }
/** * Complete the setup task. * * @since 0.1.0 * * @return void */ public function complete() { $templatesFolder = $this->getConfigKey('Folders', 'vcs'); try { $filesystem = new Filesystem(); $filesystem->removeDirectory($templatesFolder); } catch (Exception $exception) { $this->io->writeError(sprintf('Could not remove VCS folder "%1$s". Reason: %2$s', $templatesFolder, $exception->getMessage())); } }
public function tearDown() { $filesystem = new Filesystem(); $filesystem->removeDirectory($this->tmp); chdir($this->cwd); umask($this->umask); unset($this->umask); unset($this->tmp); unset($this->cwd); }
private function copyFile($from, $to) { if (!is_file($from)) { throw new \RuntimeException('Invalid PEAR package. package.xml defines file that is not located inside tarball.'); } $this->filesystem->ensureDirectoryExists(dirname($to)); if (!copy($from, $to)) { throw new \RuntimeException(sprintf('Failed to copy %s to %s', $from, $to)); } }
/** * Ensures that all required directories exist when installing the application. * * @param Event $event */ public static function ensureDirectoriesExist(Event $event) { $options = $event->getComposer()->getPackage()->getExtra(); $directories = [$options['symfony-var-dir']]; foreach ($directories as $eachDirectory) { $event->getIO()->write(sprintf('Ensuring the <comment>%s</comment> directory exists.', $eachDirectory)); $fs = new Filesystem(); $fs->ensureDirectoryExists($eachDirectory); } }
public function onPostInstallCommand(ScriptEvent $event) { $config = $event->getComposer()->getConfig(); $filesystem = new Filesystem(); $vendor_path = $filesystem->normalizePath(realpath($config->get('vendor-dir'))); $cake_dir = $filesystem->normalizePath($vendor_path . '/cakephp/cakephp'); $root_dir = $filesystem->normalizePath(realpath("")); $app_dir = $filesystem->normalizePath($root_dir . '/app'); if (!is_dir($app_dir)) { $this->copyRecursive($filesystem->normalizePath($cake_dir . '/app'), $app_dir); $index_path = $filesystem->normalizePath($app_dir . '/webroot/index.php'); $index = str_replace('define(\'CAKE_CORE_INCLUDE_PATH\', ROOT);', 'define(\'CAKE_CORE_INCLUDE_PATH\', ROOT . \'vendor\' . DS . \'cakephp\' . DS . \'cakephp\');', file_get_contents($index_path)); file_put_contents($index_path, $index); $loader_of_old_php_path = $filesystem->normalizePath($vendor_path . '/atomita/loader-of-less-than-php5.3-plugin'); if (file_exists($loader_of_old_php_path)) { $loader = <<<EOD // @generated by atomita/cakephp1-setup-plugin include(ROOT . DS . '{$config->get('vendor-dir')}' . DS . 'autoload.php'); // @end generated EOD; $config_path = $filesystem->normalizePath($app_dir . '/config/core.php'); $config = file_get_contents($config_path); if (false === strpos($config, $loader)) { file_put_contents($config_path, $config . PHP_EOL . PHP_EOL . $loader); } } } }
/** * {@inheritDoc} */ public function initialize() { if (static::isLocalUrl($this->url)) { $this->repoDir = str_replace('file://', '', $this->url); } else { $this->repoDir = $this->config->get('cache-vcs-dir') . '/' . preg_replace('{[^a-z0-9.]}i', '-', $this->url) . '/'; $util = new GitUtil(); $util->cleanEnv(); $fs = new Filesystem(); $fs->ensureDirectoryExists(dirname($this->repoDir)); if (!is_writable(dirname($this->repoDir))) { throw new \RuntimeException('Can not clone ' . $this->url . ' to access package information. The "' . dirname($this->repoDir) . '" directory is not writable by the current user.'); } if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $this->url)) { throw new \InvalidArgumentException('The source URL ' . $this->url . ' is invalid, ssh URLs should have a port number after ":".' . "\n" . 'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.'); } // update the repo if it is a valid git repository if (is_dir($this->repoDir) && 0 === $this->process->execute('git remote', $output, $this->repoDir)) { if (0 !== $this->process->execute('git remote update --prune origin', $output, $this->repoDir)) { $this->io->write('<error>Failed to update ' . $this->url . ', package information from this repository may be outdated (' . $this->process->getErrorOutput() . ')</error>'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->repoDir); $command = sprintf('git clone --mirror %s %s', escapeshellarg($this->url), escapeshellarg($this->repoDir)); if (0 !== $this->process->execute($command, $output)) { $output = $this->process->getErrorOutput(); if (0 !== $this->process->execute('git --version', $ignoredOutput)) { throw new \RuntimeException('Failed to clone ' . $this->url . ', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()); } if ($this->io->isInteractive() && preg_match('{(https?://)([^/]+)(.*)$}i', $this->url, $match) && strpos($output, 'fatal: Authentication failed') !== false) { if ($this->io->hasAuthentication($match[2])) { $auth = $this->io->getAuthentication($match[2]); } else { $this->io->write($this->url . ' requires Authentication'); $auth = array('username' => $this->io->ask('Username: '******'password' => $this->io->askAndHideAnswer('Password: '******'username']) . ':' . rawurlencode($auth['password']) . '@' . $match[2] . $match[3]; $command = sprintf('git clone --mirror %s %s', escapeshellarg($url), escapeshellarg($this->repoDir)); if (0 === $this->process->execute($command, $output)) { $this->io->setAuthentication($match[2], $auth['username'], $auth['password']); } else { $output = $this->process->getErrorOutput(); throw new \RuntimeException('Failed to clone ' . $this->url . ', could not read packages from it' . "\n\n" . $output); } } else { throw new \RuntimeException('Failed to clone ' . $this->url . ', could not read packages from it' . "\n\n" . $output); } } } } $this->getTags(); $this->getBranches(); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir') . '/' . preg_replace('{[^a-z0-9.]}i', '-', $this->url)); }