public function setUp() { parent::setUp(); $factory = new Factory(); $this->manager = $factory->createArchiveManager($factory->createConfig()); $this->targetDir = $this->testDir . '/composer_archiver_tests'; }
/** * @param string $url * @param string $token * @param bool $cacheDir * @param null $bufferIO * * @throws \Exception */ public function __construct($url, $token = '', $cacheDir = false, $bufferIO = null) { $this->url = $url; $this->io = new NullIO(); $this->log = $bufferIO ? $bufferIO : new BufferIO(); $config = Factory::createConfig(); $cfg = ['config' => []]; if ($cacheDir) { $cfg['config']['cache-dir'] = $cacheDir; } if ($token) { $cfg['config']['github-oauth'] = ['github.com' => $token]; } $config->merge($cfg); $this->cacheDir = $cacheDir; $this->io->loadConfiguration($config); $this->repository = new Repository\VcsRepository(['url' => $url, 'no-api' => false], $this->io, $config); $driver = $this->vcsDriver = $this->repository->getDriver(); if (!$driver) { throw new \Exception('No driver found for <' . $url . '>'); } $this->driver = $driver; $composerInfoMaster = $this->driver->getComposerInformation($this->driver->getRootIdentifier()); if (!$composerInfoMaster) { throw new \Exception('master must have a valid composer.json'); } $this->name = $composerInfoMaster['name']; list($this->vendorName, $this->packageName) = explode('/', $this->name); preg_match('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):)([^/]+)/(.+?)(?:\\.git|/)?$#', $this->url, $match); $this->gitHubVendorName = $match[3]; $this->gitHubRepositoryName = $match[4]; $client = new \Github\Client(); $client->authenticate($token, null, \GitHub\Client::AUTH_URL_TOKEN); $this->client = $client; }
/** * Returns a list of directory paths in which scaffold files * are to be searched for, in order to build an index * * @return string[] */ public function directories() { $composerConfig = Factory::createConfig(null, getcwd()); $vendorDir = $composerConfig->get('vendor-dir'); $globalVendorDir = Factory::createConfig(null, $composerConfig->get('home'))->get('vendor-dir'); return [$globalVendorDir, $vendorDir, getcwd() . DIRECTORY_SEPARATOR]; }
protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $preferSource = false; $preferDist = false; switch ($config->get('preferred-install')) { case 'source': $preferSource = true; break; case 'dist': $preferDist = true; break; case 'auto': default: break; } if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) { $preferSource = $input->getOption('prefer-source'); $preferDist = $input->getOption('prefer-dist'); } if ($input->getOption('no-custom-installers')) { $output->writeln('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>'); $input->setOption('no-plugins', true); } return $this->installProject($this->getIO(), $config, $input->getArgument('package'), $input->getArgument('directory'), $input->getArgument('version'), $input->getOption('stability'), $preferSource, $preferDist, !$input->getOption('no-dev'), $input->getOption('repository-url'), $input->getOption('no-plugins'), $input->getOption('no-scripts'), $input->getOption('keep-vcs'), $input->getOption('no-progress'), $input->getOption('no-install')); }
protected function initialize(InputInterface $input, OutputInterface $output) { parent::initialize($input, $output); if ($input->getOption('global') && 'composer.json' !== $input->getOption('file')) { throw new \RuntimeException('--file and --global can not be combined'); } $this->config = Factory::createConfig($this->getIO()); $configFile = $input->getOption('global') ? $this->config->get('home') . '/config.json' : $input->getOption('file'); $this->configFile = new JsonFile($configFile); $this->configSource = new JsonConfigSource($this->configFile); $authConfigFile = $input->getOption('global') ? $this->config->get('home') . '/auth.json' : dirname(realpath($input->getOption('file'))) . '/auth.json'; $this->authConfigFile = new JsonFile($authConfigFile); $this->authConfigSource = new JsonConfigSource($this->authConfigFile, true); if ($input->getOption('global') && !$this->configFile->exists()) { touch($this->configFile->getPath()); $this->configFile->write(array('config' => new \ArrayObject())); @chmod($this->configFile->getPath(), 0600); } if ($input->getOption('global') && !$this->authConfigFile->exists()) { touch($this->authConfigFile->getPath()); $this->authConfigFile->write(array('http-basic' => new \ArrayObject(), 'github-oauth' => new \ArrayObject())); @chmod($this->authConfigFile->getPath(), 0600); } if (!$this->configFile->exists()) { throw new \RuntimeException(sprintf('File "%s" cannot be found in the current directory', $configFile)); } }
/** * 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())); } } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->rfs = new RemoteFilesystem($this->getIO()); $output->write('Checking platform settings: '); $this->outputResult($output, $this->checkPlatform()); $output->write('Checking http connectivity: '); $this->outputResult($output, $this->checkHttp()); $opts = stream_context_get_options(StreamContextFactory::getContext()); if (!empty($opts['http']['proxy'])) { $output->write('Checking HTTP proxy: '); $this->outputResult($output, $this->checkHttpProxy()); $output->write('Checking HTTPS proxy support for request_fulluri: '); $this->outputResult($output, $this->checkHttpsProxyFullUriRequestParam()); } $composer = $this->getComposer(false); if ($composer) { $output->write('Checking composer.json: '); $this->outputResult($output, $this->checkComposerSchema()); } if ($composer) { $config = $composer->getConfig(); } else { $config = Factory::createConfig(); } if ($oauth = $config->get('github-oauth')) { foreach ($oauth as $domain => $token) { $output->write('Checking ' . $domain . ' oauth access: '); $this->outputResult($output, $this->checkGithubOauth($domain, $token)); } } $output->write('Checking composer version: '); $this->outputResult($output, $this->checkVersion()); return $this->failures; }
public function run(InputInterface $input, OutputInterface $output) { // extract real command name $tokens = preg_split('{\\s+}', $input->__toString()); $args = array(); foreach ($tokens as $token) { if ($token && $token[0] !== '-') { $args[] = $token; if (count($args) >= 2) { break; } } } // show help for this command if no command was found if (count($args) < 2) { return parent::run($input, $output); } // change to global dir $config = Factory::createConfig(); chdir($config->get('home')); $this->getIO()->writeError('<info>Changed current directory to ' . $config->get('home') . '</info>'); // create new input without "global" command prefix $input = new StringInput(preg_replace('{\\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\\b}', '', $input->__toString(), 1)); $this->getApplication()->resetComposer(); return $this->getApplication()->run($input, $output); }
/** * {@inheritDoc} */ protected function initialize(InputInterface $input, OutputInterface $output) { if ($input->getOption('global') && 'composer.json' !== $input->getOption('file')) { throw new \RuntimeException('--file and --global can not be combined'); } $this->config = Factory::createConfig($this->getIO()); // Get the local composer.json, global config.json, or if the user // passed in a file to use $configFile = $input->getOption('global') ? $this->config->get('home') . '/config.json' : $input->getOption('file'); $this->configFile = new JsonFile($configFile); $this->configSource = new JsonConfigSource($this->configFile); $authConfigFile = $input->getOption('global') ? $this->config->get('home') . '/auth.json' : dirname(realpath($input->getOption('file'))) . '/auth.json'; $this->authConfigFile = new JsonFile($authConfigFile); $this->authConfigSource = new JsonConfigSource($this->authConfigFile, true); // initialize the global file if it's not there if ($input->getOption('global') && !$this->configFile->exists()) { touch($this->configFile->getPath()); $this->configFile->write(array('config' => new \ArrayObject())); @chmod($this->configFile->getPath(), 0600); } if ($input->getOption('global') && !$this->authConfigFile->exists()) { touch($this->authConfigFile->getPath()); $this->authConfigFile->write(array('http-basic' => new \ArrayObject(), 'github-oauth' => new \ArrayObject())); @chmod($this->authConfigFile->getPath(), 0600); } if (!$this->configFile->exists()) { throw new \RuntimeException('No composer.json found in the current directory'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $baseUrl = (extension_loaded('openssl') ? 'https' : 'http') . '://' . self::HOMEPAGE; $config = Factory::createConfig(); $remoteFilesystem = new RemoteFilesystem($this->getIO(), $config); $cacheDir = $config->get('cache-dir'); $rollbackDir = $config->get('home'); $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; // check if current dir is writable and if not try the cache dir from settings $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir; // check for permissions in local filesystem before start connection process 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; } // remove saved installations of composer if ($input->getOption('clean-backups')) { $finder = $this->getOldInstallationFinder($rollbackDir); $fs = new Filesystem(); foreach ($finder as $file) { $file = (string) $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>'); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(false); if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $this->getIO()->write('Checking composer.json: ', false); $this->outputResult($this->checkComposerSchema()); } if ($composer) { $config = $composer->getConfig(); } else { $config = Factory::createConfig(); } $this->rfs = new RemoteFilesystem($this->getIO(), $config); $this->process = new ProcessExecutor($this->getIO()); $this->getIO()->write('Checking platform settings: ', false); $this->outputResult($this->checkPlatform()); $this->getIO()->write('Checking git settings: ', false); $this->outputResult($this->checkGit()); $this->getIO()->write('Checking http connectivity: ', false); $this->outputResult($this->checkHttp()); $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org')); if (!empty($opts['http']['proxy'])) { $this->getIO()->write('Checking HTTP proxy: ', false); $this->outputResult($this->checkHttpProxy()); $this->getIO()->write('Checking HTTP proxy support for request_fulluri: ', false); $this->outputResult($this->checkHttpProxyFullUriRequestParam()); $this->getIO()->write('Checking HTTPS proxy support for request_fulluri: ', false); $this->outputResult($this->checkHttpsProxyFullUriRequestParam()); } if ($oauth = $config->get('github-oauth')) { foreach ($oauth as $domain => $token) { $this->getIO()->write('Checking ' . $domain . ' oauth access: ', false); $this->outputResult($this->checkGithubOauth($domain, $token)); } } else { $this->getIO()->write('Checking github.com rate limit: ', false); try { $rate = $this->getGithubRateLimit('github.com'); $this->outputResult(true); if (10 > $rate['remaining']) { $this->getIO()->write('<warning>WARNING</warning>'); $this->getIO()->write(sprintf('<comment>Github has a rate limit on their API. ' . 'You currently have <options=bold>%u</options=bold> ' . 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL . ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>', $rate['remaining'], $rate['limit'])); } } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 401) { $this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>'); } else { $this->outputResult($e); } } } $this->getIO()->write('Checking disk free space: ', false); $this->outputResult($this->checkDiskSpace($config)); $this->getIO()->write('Checking composer version: ', false); $this->outputResult($this->checkVersion()); return $this->failures; }
private function getDownloadManager() { if (!$this->downloadManager) { $config = Factory::createConfig(); $factory = new Factory(); $this->downloadManager = $factory->createDownloadManager($this->getIO(), $config); } return $this->downloadManager; }
/** * @return \Composer\Config */ public static function loadConfiguration() { try { $configuration = Factory::createConfig(); } catch (Exception $e) { throw RuntimeException::fromAnyException($e); } return $configuration; }
/** * {@inheritDoc} * * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * * @throws FilesystemException When the temporary directory or local file are not writable. */ protected function execute(InputInterface $input, OutputInterface $output) { $originName = $this->getOriginName(); $config = Factory::createConfig(); $inputOutput = $this->getIO(); $this->rfs = new RemoteFilesystem($inputOutput, $config); $cacheDir = $config->get('cache-dir'); $rollbackDir = $config->get('home'); $localFilename = $this->determineLocalFileName(); // check if current dir is writable and if not try the cache dir from settings $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir; // check for permissions in local filesystem before start connection process if (!is_writable($tmpDir)) { throw new FilesystemException(sprintf('Self update failed: the "%s" directory used to download the temp file could not be written', $tmpDir)); } if (!is_writable($localFilename)) { throw new FilesystemException('Self update failed: "' . $localFilename . '" is not writable.'); } if ($input->getOption('rollback')) { return $this->rollback($rollbackDir, $localFilename); } $latestVersion = $this->getLatestVersion(); $updateVersion = $input->getArgument('version') ?: $latestVersion; if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) { $inputOutput->writeError('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>'); return 1; } if (Tenside::VERSION === $updateVersion) { $inputOutput->writeError('<info>You are already using version ' . $updateVersion . '.</info>'); return 0; } $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar') . '-temp.phar'; $backupFile = sprintf('%s/%s-%s%s', $rollbackDir, strtr(Tenside::RELEASE_DATE, ' :', '_-'), preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Tenside::VERSION), self::OLD_INSTALL_EXT); $inputOutput->writeError(sprintf('Updating to version <info>%s</info>.', $updateVersion)); $remoteFilename = $this->determineRemoteFilename($updateVersion); $this->rfs->copy($originName, $remoteFilename, $tempFilename, !$input->getOption('no-progress')); if (!file_exists($tempFilename)) { $inputOutput->writeError('<error>The download of the new version failed for an unexpected reason</error>'); return 1; } // remove saved installations of tenside if ($input->getOption('clean-backups')) { $this->cleanupOldBackups($rollbackDir); } if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) { $inputOutput->writeError('<error>The file is corrupted (' . $err->getMessage() . ').</error>'); $inputOutput->writeError('<error>Please re-run the self-update command to try again.</error>'); return 1; } if (file_exists($backupFile)) { $inputOutput->writeError(sprintf('Use <info>%s self-update --rollback</info> to return to version %s', $localFilename, Tenside::VERSION)); return 0; } $inputOutput->writeError(sprintf('<warning>A backup of the current version could not be written to %s, ' . 'no rollback possible</warning>', $backupFile)); return 0; }
protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $this->updatePreferredOptions($config, $input, $preferSource, $preferDist, true); if ($input->getOption('no-custom-installers')) { $this->getIO()->writeError('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>'); $input->setOption('no-plugins', true); } return $this->installProject($this->getIO(), $config, $input->getArgument('package'), $input->getArgument('directory'), $input->getArgument('version'), $input->getOption('stability'), $preferSource, $preferDist, !$input->getOption('no-dev'), $input->getOption('repository-url'), $input->getOption('no-plugins'), $input->getOption('no-scripts'), $input->getOption('keep-vcs'), $input->getOption('no-progress'), $input->getOption('no-install'), $input->getOption('ignore-platform-reqs'), $input); }
public function installProject(IOInterface $io, $packageName, $directory = null, $version = null, $preferSource = false, $installDevPackages = false, $repositoryUrl = null, $disableCustomInstallers = false, $noScripts = false) { $dm = $this->createDownloadManager($io); if ($preferSource) { $dm->setPreferSource(true); } $config = Factory::createConfig(); if (null === $repositoryUrl) { $sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config)); } elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION)) { $sourceRepo = new FilesystemRepository(new JsonFile($repositoryUrl, new RemoteFilesystem($io))); } elseif (0 === strpos($repositoryUrl, 'http')) { $sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config); } else { throw new \InvalidArgumentException("Invalid repository url given. Has to be a .json file or an http url."); } $candidates = $sourceRepo->findPackages($packageName, $version); if (!$candidates) { throw new \InvalidArgumentException("Could not find package {$packageName}" . ($version ? " with version {$version}." : '')); } if (null === $directory) { $parts = explode("/", $packageName, 2); $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts); } // select highest version if we have many $package = $candidates[0]; foreach ($candidates as $candidate) { if (version_compare($package->getVersion(), $candidate->getVersion(), '<')) { $package = $candidate; } } $io->write('<info>Installing ' . $package->getName() . ' (' . VersionParser::formatVersion($package, false) . ')</info>', true); if ($disableCustomInstallers) { $io->write('<info>Custom installers have been disabled.</info>'); } if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) { $package->setSourceReference(substr($package->getPrettyVersion(), 4)); } $projectInstaller = new ProjectInstaller($directory, $dm); $projectInstaller->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), $package); if ($package->getRepository() instanceof NotifiableRepositoryInterface) { $package->getRepository()->notifyInstall($package); } $io->write('<info>Created project in ' . $directory . '</info>', true); chdir($directory); putenv('COMPOSER_ROOT_VERSION=' . $package->getPrettyVersion()); $composer = Factory::create($io); $installer = Installer::create($io, $composer); $installer->setPreferSource($preferSource)->setDevMode($installDevPackages)->setRunScripts(!$noScripts); if ($disableCustomInstallers) { $installer->disableCustomInstallers(); } $installer->run(); }
/** * Validate repository URL * * @param $repositoryUrl * @return bool */ protected function isRepositoryValid($repositoryUrl) { $io = new NullIO(); $config = Factory::createConfig(); $io->loadConfiguration($config); $repository = new VcsRepository(array('url' => $repositoryUrl), $io, $config); if (!($driver = $repository->getDriver())) { return false; } $information = $driver->getComposerInformation($driver->getRootIdentifier()); return !empty($information['name']); }
/** * @return RepositoryInterface[] */ public static function defaultRepos(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null) { if (!$config) { $config = Factory::createConfig($io); } if (!$rm) { if (!$io) { throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager'); } $rm = static::manager($io, $config, null, Factory::createRemoteFilesystem($io, $config)); } return static::createRepos($rm, $config->getRepositories()); }
protected function execute(InputInterface $input, OutputInterface $output) { // init repos $platformRepo = new PlatformRepository(); if ($composer = $this->getComposer(false)) { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $installedRepo = new CompositeRepository(array($localRepo, $platformRepo)); $repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories())); } else { $output->writeln('No composer.json found in the current directory, showing packages from packagist.org'); $installedRepo = $platformRepo; $packagist = new ComposerRepository(array('url' => 'http://packagist.org'), $this->getIO(), Factory::createConfig()); $repos = new CompositeRepository(array($installedRepo, $packagist)); } $tokens = $input->getArgument('tokens'); $packages = array(); $maxPackageLength = 0; foreach ($repos->getPackages() as $package) { if ($package instanceof AliasPackage || isset($packages[$package->getName()])) { continue; } foreach ($tokens as $token) { if (!($score = $this->matchPackage($package, $token))) { continue; } if (false !== ($pos = stripos($package->getName(), $token))) { $name = substr($package->getPrettyName(), 0, $pos) . '<highlight>' . substr($package->getPrettyName(), $pos, strlen($token)) . '</highlight>' . substr($package->getPrettyName(), $pos + strlen($token)); } else { $name = $package->getPrettyName(); } $description = strtok($package->getDescription(), "\r\n"); if (false !== ($pos = stripos($description, $token))) { $description = substr($description, 0, $pos) . '<highlight>' . substr($description, $pos, strlen($token)) . '</highlight>' . substr($description, $pos + strlen($token)); } $packages[$package->getName()] = array('name' => $name, 'description' => $description, 'length' => $length = strlen($package->getPrettyName()), 'score' => $score); $maxPackageLength = max($maxPackageLength, $length); continue 2; } } usort($packages, function ($a, $b) { if ($a['score'] === $b['score']) { return 0; } return $a['score'] > $b['score'] ? -1 : 1; }); foreach ($packages as $details) { $extraSpaces = $maxPackageLength - $details['length']; $output->writeln($details['name'] . str_repeat(' ', $extraSpaces) . ' <comment>:</comment> ' . $details['description']); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $verbose = $input->getOption('verbose'); $force = $input->getOption('force'); $package = $input->getArgument('package'); $doctrine = $this->getContainer()->get('doctrine'); $router = $this->getContainer()->get('router'); $flags = 0; if ($package) { $packages = array(array('id' => $doctrine->getRepository('PackagistWebBundle:Package')->findOneByName($package)->getId())); $flags = Updater::UPDATE_TAGS; } elseif ($force) { $packages = $doctrine->getEntityManager()->getConnection()->fetchAll('SELECT id FROM package ORDER BY id ASC'); $flags = Updater::UPDATE_TAGS; } else { $packages = $doctrine->getRepository('PackagistWebBundle:Package')->getStalePackages(); } $ids = array(); foreach ($packages as $package) { $ids[] = $package['id']; } if ($input->getOption('delete-before')) { $flags = Updater::DELETE_BEFORE; } $updater = $this->getContainer()->get('packagist.package_updater'); $start = new \DateTime(); $input->setInteractive(false); $io = $verbose ? new ConsoleIO($input, $output, $this->getApplication()->getHelperSet()) : new NullIO(); $config = Factory::createConfig(); $loader = new ValidatingArrayLoader(new ArrayLoader()); while ($ids) { $packages = $doctrine->getRepository('PackagistWebBundle:Package')->getPackagesWithVersions(array_splice($ids, 0, 50)); foreach ($packages as $package) { if ($verbose) { $output->writeln('Importing ' . $package->getRepository()); } try { $repository = new VcsRepository(array('url' => $package->getRepository()), $io, $config); $repository->setLoader($loader); $updater->update($package, $repository, $flags, $start); } catch (\Exception $e) { $output->writeln('<error>Exception: ' . $e->getMessage() . ' at ' . $e->getFile() . ':' . $e->getLine() . ', skipping package ' . $router->generate('view_package', array('name' => $package->getName()), true) . '</error>'); } } $doctrine->getEntityManager()->clear(); unset($packages); } }
protected function archive(IOInterface $io, $packageName = null, $version = null, $format = 'tar', $dest = '.') { $config = Factory::createConfig(); $factory = new Factory(); $archiveManager = $factory->createArchiveManager($config); if ($packageName) { $package = $this->selectPackage($io, $packageName, $version); if (!$package) { return 1; } } else { $package = $this->getComposer()->getPackage(); } $io->write('<info>Creating the archive.</info>'); $archiveManager->archive($package, $format, $dest); return 0; }
protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $io = $this->getIO(); $cachePath = realpath($config->get('cache-repo-dir')); if (!$cachePath) { $io->write('<info>Cache directory does not exist.</info>'); return; } $cache = new Cache($io, $cachePath); if (!$cache->isEnabled()) { $io->write('<info>Cache is not enabled.</info>'); return; } $io->write('<info>Clearing cache in: ' . $cachePath . '</info>'); $cache->gc(0, 0); $io->write('<info>Cache cleared.</info>'); }
protected function initialize(InputInterface $input, OutputInterface $output) { if ($input->getOption('global') && 'composer.json' !== $input->getOption('file')) { throw new \RuntimeException('--file and --global can not be combined'); } $this->config = Factory::createConfig(); $configFile = $input->getOption('global') ? $this->config->get('home') . '/config.json' : $input->getOption('file'); $this->configFile = new JsonFile($configFile); $this->configSource = new JsonConfigSource($this->configFile); if ($input->getOption('global') && !$this->configFile->exists()) { touch($this->configFile->getPath()); $this->configFile->write(array('config' => new \ArrayObject())); @chmod($this->configFile->getPath(), 0600); } if (!$this->configFile->exists()) { throw new \RuntimeException('No composer.json found in the current directory'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $composer = $this->getComposer(false); if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $output->write('Checking composer.json: '); $this->outputResult($output, $this->checkComposerSchema()); } if ($composer) { $config = $composer->getConfig(); } else { $config = Factory::createConfig(); } $this->rfs = new RemoteFilesystem($this->getIO(), $config); $this->process = new ProcessExecutor($this->getIO()); $output->write('Checking platform settings: '); $this->outputResult($output, $this->checkPlatform()); $output->write('Checking git settings: '); $this->outputResult($output, $this->checkGit()); $output->write('Checking http connectivity: '); $this->outputResult($output, $this->checkHttp()); $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org')); if (!empty($opts['http']['proxy'])) { $output->write('Checking HTTP proxy: '); $this->outputResult($output, $this->checkHttpProxy()); $output->write('Checking HTTP proxy support for request_fulluri: '); $this->outputResult($output, $this->checkHttpProxyFullUriRequestParam()); $output->write('Checking HTTPS proxy support for request_fulluri: '); $this->outputResult($output, $this->checkHttpsProxyFullUriRequestParam()); } if ($oauth = $config->get('github-oauth')) { foreach ($oauth as $domain => $token) { $output->write('Checking ' . $domain . ' oauth access: '); $this->outputResult($output, $this->checkGithubOauth($domain, $token)); } } $output->write('Checking disk free space: '); $this->outputResult($output, $this->checkDiskSpace($config)); $output->write('Checking composer version: '); $this->outputResult($output, $this->checkVersion()); return $this->failures; }
protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $composer = $this->getComposer(false); if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'archive', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_ARCHIVE_CMD); } if (null === $input->getOption('format')) { $input->setOption('format', $config->get('archive-format')); } if (null === $input->getOption('dir')) { $input->setOption('dir', $config->get('archive-dir')); } $returnCode = $this->archive($this->getIO(), $config, $input->getArgument('package'), $input->getArgument('version'), $input->getOption('format'), $input->getOption('dir'), $input->getOption('file')); if (0 === $returnCode && $composer) { $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ARCHIVE_CMD); } return $returnCode; }
protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $io = $this->getIO(); $cachePaths = array('cache-dir' => $config->get('cache-dir'), 'cache-files-dir' => $config->get('cache-files-dir'), 'cache-repo-dir' => $config->get('cache-repo-dir'), 'cache-vcs-dir' => $config->get('cache-vcs-dir')); foreach ($cachePaths as $key => $cachePath) { $cachePath = realpath($cachePath); if (!$cachePath) { $io->writeError("<info>Cache directory does not exist ({$key}): {$cachePath}</info>"); continue; } $cache = new Cache($io, $cachePath); if (!$cache->isEnabled()) { $io->writeError("<info>Cache is not enabled ({$key}): {$cachePath}</info>"); continue; } $io->writeError("<info>Clearing cache ({$key}): {$cachePath}</info>"); $cache->gc(0, 0); } $io->writeError('<info>All caches cleared.</info>'); }
public function run(InputInterface $input, OutputInterface $output) { $tokens = preg_split('{\\s+}', $input->__toString()); $args = array(); foreach ($tokens as $token) { if ($token && $token[0] !== '-') { $args[] = $token; if (count($args) >= 2) { break; } } } if (count($args) < 2) { return parent::run($input, $output); } $config = Factory::createConfig(); chdir($config->get('home')); $this->getIO()->writeError('<info>Changed current directory to ' . $config->get('home') . '</info>'); $input = new StringInput(preg_replace('{\\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\\b}', '', $input->__toString(), 1)); return $this->getApplication()->run($input, $output); }
protected function execute(InputInterface $input, OutputInterface $output) { $config = Factory::createConfig(); $preferSource = false; $preferDist = false; switch ($config->get('preferred-install')) { case 'source': $preferSource = true; break; case 'dist': $preferDist = true; break; case 'auto': default: // noop break; } if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) { $preferSource = $input->getOption('prefer-source'); $preferDist = $input->getOption('prefer-dist'); } return $this->installProject($this->getIO(), $config, $input->getArgument('package'), $input->getArgument('directory'), $input->getArgument('version'), $input->getOption('stability'), $preferSource, $preferDist, $input->getOption('dev'), $input->getOption('repository-url'), $input->getOption('no-custom-installers'), $input->getOption('no-scripts'), $input->getOption('keep-vcs'), $input->getOption('no-progress')); }
/** * {@inheritDoc} */ protected function initialize(InputInterface $input, OutputInterface $output) { parent::initialize($input, $output); if ($input->getOption('global') && null !== $input->getOption('file')) { throw new \RuntimeException('--file and --global can not be combined'); } $io = $this->getIO(); $this->config = Factory::createConfig($io); // Get the local composer.json, global config.json, or if the user // passed in a file to use $configFile = $input->getOption('global') ? $this->config->get('home') . '/config.json' : ($input->getOption('file') ?: trim(getenv('COMPOSER')) ?: 'composer.json'); // Create global composer.json if this was invoked using `composer global config` if ($configFile === 'composer.json' && !file_exists($configFile) && realpath(getcwd()) === realpath($this->config->get('home'))) { file_put_contents($configFile, "{\n}\n"); } $this->configFile = new JsonFile($configFile, null, $io); $this->configSource = new JsonConfigSource($this->configFile); $authConfigFile = $input->getOption('global') ? $this->config->get('home') . '/auth.json' : dirname(realpath($configFile)) . '/auth.json'; $this->authConfigFile = new JsonFile($authConfigFile, null, $io); $this->authConfigSource = new JsonConfigSource($this->authConfigFile, true); // Initialize the global file if it's not there, ignoring any warnings or notices if ($input->getOption('global') && !$this->configFile->exists()) { touch($this->configFile->getPath()); $this->configFile->write(array('config' => new \ArrayObject())); Silencer::call('chmod', $this->configFile->getPath(), 0600); } if ($input->getOption('global') && !$this->authConfigFile->exists()) { touch($this->authConfigFile->getPath()); $this->authConfigFile->write(array('http-basic' => new \ArrayObject(), 'github-oauth' => new \ArrayObject(), 'gitlab-oauth' => new \ArrayObject())); Silencer::call('chmod', $this->authConfigFile->getPath(), 0600); } if (!$this->configFile->exists()) { throw new \RuntimeException(sprintf('File "%s" cannot be found in the current directory', $configFile)); } }
/** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { $git = $this->getGitConfig(); $io = $this->getIO(); $formatter = $this->getHelperSet()->get('formatter'); // initialize repos if configured $repositories = $input->getOption('repository'); if ($repositories) { $config = Factory::createConfig($io); $repos = array(new PlatformRepository()); foreach ($repositories as $repo) { $repos[] = RepositoryFactory::fromString($io, $config, $repo); } $repos[] = RepositoryFactory::createRepo($io, $config, array('type' => 'composer', 'url' => 'https://packagist.org')); $this->repos = new CompositeRepository($repos); unset($repos, $config, $repositories); } $io->writeError(array('', $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true), '')); // namespace $io->writeError(array('', 'This command will guide you through creating your composer.json config.', '')); $cwd = realpath("."); if (!($name = $input->getOption('name'))) { $name = basename($cwd); $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name); $name = strtolower($name); if (isset($git['github.user'])) { $name = $git['github.user'] . '/' . $name; } elseif (!empty($_SERVER['USERNAME'])) { $name = $_SERVER['USERNAME'] . '/' . $name; } elseif (get_current_user()) { $name = get_current_user() . '/' . $name; } else { // package names must be in the format foo/bar $name = $name . '/' . $name; } $name = strtolower($name); } else { if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) { throw new \InvalidArgumentException('The package name ' . $name . ' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'); } } $name = $io->askAndValidate('Package name (<vendor>/<name>) [<comment>' . $name . '</comment>]: ', function ($value) use($name) { if (null === $value) { return $name; } if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) { throw new \InvalidArgumentException('The package name ' . $value . ' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'); } return $value; }, null, $name); $input->setOption('name', $name); $description = $input->getOption('description') ?: false; $description = $io->ask('Description [<comment>' . $description . '</comment>]: ', $description); $input->setOption('description', $description); if (null === ($author = $input->getOption('author'))) { if (isset($git['user.name']) && isset($git['user.email'])) { $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']); } } $self = $this; $author = $io->askAndValidate('Author [<comment>' . $author . '</comment>, n to skip]: ', function ($value) use($self, $author) { if ($value === 'n' || $value === 'no') { return; } $value = $value ?: $author; $author = $self->parseAuthorString($value); return sprintf('%s <%s>', $author['name'], $author['email']); }, null, $author); $input->setOption('author', $author); $minimumStability = $input->getOption('stability') ?: null; $minimumStability = $io->askAndValidate('Minimum Stability [<comment>' . $minimumStability . '</comment>]: ', function ($value) use($self, $minimumStability) { if (null === $value) { return $minimumStability; } if (!isset(BasePackage::$stabilities[$value])) { throw new \InvalidArgumentException('Invalid minimum stability "' . $value . '". Must be empty or one of: ' . implode(', ', array_keys(BasePackage::$stabilities))); } return $value; }, null, $minimumStability); $input->setOption('stability', $minimumStability); $type = $input->getOption('type') ?: false; $type = $io->ask('Package Type (e.g. library, project, metapackage, composer-plugin) [<comment>' . $type . '</comment>]: ', $type); $input->setOption('type', $type); $license = $input->getOption('license') ?: false; $license = $io->ask('License [<comment>' . $license . '</comment>]: ', $license); $input->setOption('license', $license); $io->writeError(array('', 'Define your dependencies.', '')); $question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? '; $requirements = array(); if ($io->askConfirmation($question, true)) { $requirements = $this->determineRequirements($input, $output, $input->getOption('require')); } $input->setOption('require', $requirements); $question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? '; $devRequirements = array(); if ($io->askConfirmation($question, true)) { $devRequirements = $this->determineRequirements($input, $output, $input->getOption('require-dev')); } $input->setOption('require-dev', $devRequirements); }