Beispiel #1
0
 protected function selectPackage(IOInterface $io, $packageName, $version = null)
 {
     $io->writeError('<info>Searching for the specified package.</info>');
     if ($composer = $this->getComposer(false)) {
         $localRepo = $composer->getRepositoryManager()->getLocalRepository();
         $repos = new CompositeRepository(array_merge(array($localRepo), $composer->getRepositoryManager()->getRepositories()));
     } else {
         $defaultRepos = Factory::createDefaultRepositories($this->getIO());
         $io->writeError('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos)));
         $repos = new CompositeRepository($defaultRepos);
     }
     $pool = new Pool();
     $pool->addRepository($repos);
     $parser = new VersionParser();
     $constraint = $version ? $parser->parseConstraints($version) : null;
     $packages = $pool->whatProvides($packageName, $constraint, true);
     if (count($packages) > 1) {
         $package = reset($packages);
         $io->writeError('<info>Found multiple matches, selected ' . $package->getPrettyString() . '.</info>');
         $io->writeError('Alternatives were ' . implode(', ', array_map(function ($p) {
             return $p->getPrettyString();
         }, $packages)) . '.');
         $io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>');
     } elseif ($packages) {
         $package = reset($packages);
         $io->writeError('<info>Found an exact match ' . $package->getPrettyString() . '.</info>');
     } else {
         $io->writeError('<error>Could not find a package matching ' . $packageName . '.</error>');
         return false;
     }
     return $package;
 }
Beispiel #2
0
 protected function prepare()
 {
     if (Type::determinePickle($this->path, $matches) < 1) {
         throw new \Exception('Not a pickle git URI');
     }
     $this->name = $matches['package'];
     $extension = $this->fetchPackageJson();
     $versionParser = new VersionParser();
     if ($matches['version'] == '') {
         $versions = array_keys($extension['packages'][$this->name]);
         if (count($versions) > 1) {
             $versionToUse = $versions[1];
         } else {
             $versionToUse = $versions[0];
         }
     } else {
         $versionConstraints = $versionParser->parseConstraints($matches['version']);
         /* versions are sorted decreasing */
         foreach ($extension['packages'][$this->name] as $version => $release) {
             $constraint = new VersionConstraint('=', $versionParser->normalize($version));
             if ($versionConstraints->matches($constraint)) {
                 $versionToUse = $version;
                 break;
             }
         }
     }
     $package = $extension['packages'][$this->name][$versionToUse];
     $this->version = $versionToUse;
     $this->normalizedVersion = $versionParser->normalize($versionToUse);
     $this->name = $matches['package'];
     $this->prettyVersion = $this->version;
     $this->url = $package['source']['url'];
     $this->reference = $package['source']['reference'];
     $this->type = $package['source']['type'];
 }
Beispiel #3
0
 /**
  * Search for a given package version.
  *
  * Usage examples : Composition::has('php', '5.3.*') // PHP version
  *                  Composition::has('ext-memcache') // PHP extension
  *                  Composition::has('vendor/package', '>2.1') // Package version
  *
  * @param type $packageName  The package name
  * @param type $prettyString An optional version constraint
  *
  * @return boolean           Wether or not the package has been found.
  */
 public static function has($packageName, $prettyString = '*')
 {
     if (null === self::$pool) {
         if (null === self::$rootDir) {
             self::$rootDir = getcwd();
             if (!file_exists(self::$rootDir . '/composer.json')) {
                 throw new \RuntimeException('Unable to guess the project root dir, please specify it manually using the Composition::setRootDir method.');
             }
         }
         $minimumStability = 'dev';
         $config = new Config();
         $file = new JsonFile(self::$rootDir . '/composer.json');
         if ($file->exists()) {
             $projectConfig = $file->read();
             $config->merge($projectConfig);
             if (isset($projectConfig['minimum-stability'])) {
                 $minimumStability = $projectConfig['minimum-stability'];
             }
         }
         $vendorDir = self::$rootDir . '/' . $config->get('vendor-dir');
         $pool = new Pool($minimumStability);
         $pool->addRepository(new PlatformRepository());
         $pool->addRepository(new InstalledFilesystemRepository(new JsonFile($vendorDir . '/composer/installed.json')));
         $pool->addRepository(new InstalledFilesystemRepository(new JsonFile($vendorDir . '/composer/installed_dev.json')));
         self::$pool = $pool;
     }
     $parser = new VersionParser();
     $constraint = $parser->parseConstraints($prettyString);
     $packages = self::$pool->whatProvides($packageName, $constraint);
     return empty($packages) ? false : true;
 }
Beispiel #4
0
 /**
  * Tests memory package marshalling/serialization semantics
  * @dataProvider providerVersioningSchemes
  */
 public function testMemoryPackageHasExpectedMarshallingSemantics($name, $version)
 {
     $versionParser = new VersionParser();
     $normVersion = $versionParser->normalize($version);
     $package = new MemoryPackage($name, $normVersion, $version);
     $this->assertEquals(strtolower($name) . '-' . $normVersion, (string) $package);
 }
 /**
  * Checks PHP version
  *
  * @return array
  */
 public function checkPhpVersion()
 {
     try {
         $requiredVersion = $this->composerInformation->getRequiredPhpVersion();
     } catch (\Exception $e) {
         return [
             'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR,
             'data' => [
                 'error' => 'phpVersionError',
                 'message' => 'Cannot determine required PHP version: ' . $e->getMessage()
             ],
         ];
     }
     $multipleConstraints = $this->versionParser->parseConstraints($requiredVersion);
     try {
         $normalizedPhpVersion = $this->versionParser->normalize(PHP_VERSION);
     } catch (\UnexpectedValueException $e) {
         $prettyVersion = preg_replace('#^([^~+-]+).*$#', '$1', PHP_VERSION);
         $normalizedPhpVersion = $this->versionParser->normalize($prettyVersion);
     }
     $currentPhpVersion = $this->versionParser->parseConstraints($normalizedPhpVersion);
     $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS;
     if (!$multipleConstraints->matches($currentPhpVersion)) {
         $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR;
     }
     return [
         'responseType' => $responseType,
         'data' => [
             'required' => $requiredVersion,
             'current' => PHP_VERSION,
         ],
     ];
 }
 /**
  * @param PackageInterface $package
  * @param bool             $allowDevMaster
  *
  * @return \string[]
  */
 public function validatePackage(PackageInterface $package, $allowDevMaster = false)
 {
     $errors = [];
     $versionParser = new VersionParser();
     /** @noinspection ExceptionsAnnotatingAndHandlingInspection */
     $devMaster = new Constraint('==', $versionParser->normalize('dev-master'));
     foreach ($package->getRequires() as $link) {
         $linkConstraint = $link->getConstraint();
         if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
             continue;
         }
         if ($linkConstraint->matches($devMaster)) {
             if ($allowDevMaster) {
                 continue;
             }
             $errors[] = sprintf('Package "%s" is required with branch constraint %s', $link->getTarget(), $linkConstraint->getPrettyString());
         }
         $constraints = [$linkConstraint];
         if ($linkConstraint instanceof MultiConstraint) {
             $constraints = (new ConstraintAccessor($linkConstraint))->getConstraints();
         }
         foreach ($constraints as $constraint) {
             if ('dev-' === substr($constraint->getPrettyString(), 0, 4)) {
                 $errors[] = sprintf('Package "%s" is required with branch constraint %s', $link->getTarget(), $linkConstraint->getPrettyString());
             }
         }
     }
     return $errors;
 }
 /**
  * {@inheritDoc}
  */
 public function getMinimalPackages()
 {
     if (isset($this->minimalPackages)) {
         return $this->minimalPackages;
     }
     if (null === $this->rawData) {
         $this->rawData = $this->loadDataFromServer();
     }
     $this->minimalPackages = array();
     $versionParser = new VersionParser();
     foreach ($this->rawData as $package) {
         $version = !empty($package['version_normalized']) ? $package['version_normalized'] : $versionParser->normalize($package['version']);
         $data = array('name' => strtolower($package['name']), 'repo' => $this, 'version' => $version, 'raw' => $package);
         if (!empty($package['replace'])) {
             $data['replace'] = $package['replace'];
         }
         if (!empty($package['provide'])) {
             $data['provide'] = $package['provide'];
         }
         // add branch aliases
         if ($aliasNormalized = $this->loader->getBranchAlias($package)) {
             $data['alias'] = preg_replace('{(\\.9{7})+}', '.x', $aliasNormalized);
             $data['alias_normalized'] = $aliasNormalized;
         }
         $this->minimalPackages[] = $data;
     }
     return $this->minimalPackages;
 }
 protected function initialize()
 {
     parent::initialize();
     $versionParser = new VersionParser();
     try {
         $prettyVersion = PHP_VERSION;
         $version = $versionParser->normalize($prettyVersion);
     } catch (\UnexpectedValueException $e) {
         $prettyVersion = preg_replace('#^(.+?)(-.+)?$#', '$1', PHP_VERSION);
         $version = $versionParser->normalize($prettyVersion);
     }
     $php = new MemoryPackage('php', $version, $prettyVersion);
     $php->setDescription('The PHP interpreter');
     parent::addPackage($php);
     foreach (get_loaded_extensions() as $name) {
         if (in_array($name, array('standard', 'Core'))) {
             continue;
         }
         $reflExt = new \ReflectionExtension($name);
         try {
             $prettyVersion = $reflExt->getVersion();
             $version = $versionParser->normalize($prettyVersion);
         } catch (\UnexpectedValueException $e) {
             $prettyVersion = '0';
             $version = $versionParser->normalize($prettyVersion);
         }
         $ext = new MemoryPackage('ext-' . $name, $version, $prettyVersion);
         $ext->setDescription('The ' . $name . ' PHP extension');
         parent::addPackage($ext);
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!$this->deploymentConfig->isAvailable()) {
         $output->writeln("<info>No information is available: the Magento application is not installed.</info>");
         return;
     }
     /** @var DbVersionInfo $dbVersionInfo */
     $dbVersionInfo = $this->objectManagerProvider->get()->get('Magento\\Framework\\Module\\DbVersionInfo');
     $outdated = $dbVersionInfo->getDbVersionErrors();
     if (!empty($outdated)) {
         $output->writeln("<info>The module code base doesn't match the DB schema and data.</info>");
         $versionParser = new VersionParser();
         $codebaseUpdateNeeded = false;
         foreach ($outdated as $row) {
             if (!$codebaseUpdateNeeded && $row[DbVersionInfo::KEY_CURRENT] !== 'none') {
                 // check if module code base update is needed
                 $currentVersion = $versionParser->parseConstraints($row[DbVersionInfo::KEY_CURRENT]);
                 $requiredVersion = $versionParser->parseConstraints('>' . $row[DbVersionInfo::KEY_REQUIRED]);
                 if ($requiredVersion->matches($currentVersion)) {
                     $codebaseUpdateNeeded = true;
                 }
             }
             $output->writeln(sprintf("<info>%20s %10s: %11s  ->  %-11s</info>", $row[DbVersionInfo::KEY_MODULE], $row[DbVersionInfo::KEY_TYPE], $row[DbVersionInfo::KEY_CURRENT], $row[DbVersionInfo::KEY_REQUIRED]));
         }
         if ($codebaseUpdateNeeded) {
             $output->writeln('<info>Some modules use code versions newer or older than the database. ' . "First update the module code, then run 'setup:upgrade'.</info>");
             // we must have an exit code higher than zero to indicate something was wrong
             return \Magento\Framework\Console\Cli::RETURN_FAILURE;
         } else {
             $output->writeln("<info>Run 'setup:upgrade' to update your DB schema and data.</info>");
         }
     } else {
         $output->writeln('<info>All modules are up to date.</info>');
     }
 }
Beispiel #10
0
 public function updateVersion()
 {
     /* Be sure package root is set before! */
     $version = new Header\Version($this);
     $parser = new VersionParser();
     $this->version = $parser->normalize($version);
     $this->prettyVersion = (string) $version;
 }
 /**
  * Return true if $version matches $constraint (expressed as a Composer constraint string)
  *
  * @param  string $version
  * @param  string $constraint
  * @return bool
  */
 public function isVersionMatching($version, $constraint)
 {
     $versionParser = new VersionParser();
     $normalizedVersion = $versionParser->normalize($version);
     $versionAsContraint = $versionParser->parseConstraints($normalizedVersion);
     $linkConstraint = $versionParser->parseConstraints($constraint);
     return $linkConstraint->matches($versionAsContraint);
 }
Beispiel #12
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = Factory::getComposerFile();
     if (!file_exists($file) && !file_put_contents($file, "{\n}\n")) {
         $output->writeln('<error>' . $file . ' could not be created.</error>');
         return 1;
     }
     if (!is_readable($file)) {
         $output->writeln('<error>' . $file . ' is not readable.</error>');
         return 1;
     }
     if (!is_writable($file)) {
         $output->writeln('<error>' . $file . ' is not writable.</error>');
         return 1;
     }
     $json = new JsonFile($file);
     $composer = $json->read();
     $composerBackup = file_get_contents($json->getPath());
     $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'));
     $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
     $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
     $baseRequirements = array_key_exists($requireKey, $composer) ? $composer[$requireKey] : array();
     $requirements = $this->formatRequirements($requirements);
     // validate requirements format
     $versionParser = new VersionParser();
     foreach ($requirements as $constraint) {
         $versionParser->parseConstraints($constraint);
     }
     if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey, $removeKey)) {
         foreach ($requirements as $package => $version) {
             $baseRequirements[$package] = $version;
             if (isset($composer[$removeKey][$package])) {
                 unset($composer[$removeKey][$package]);
             }
         }
         $composer[$requireKey] = $baseRequirements;
         $json->write($composer);
     }
     $output->writeln('<info>' . $file . ' has been updated</info>');
     if ($input->getOption('no-update')) {
         return 0;
     }
     $updateDevMode = !$input->getOption('update-no-dev');
     // Update packages
     $composer = $this->getComposer();
     $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
     $io = $this->getIO();
     $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
     $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
     $install = Installer::create($io, $composer);
     $install->setVerbose($input->getOption('verbose'))->setPreferSource($input->getOption('prefer-source'))->setPreferDist($input->getOption('prefer-dist'))->setDevMode($updateDevMode)->setUpdate(true)->setUpdateWhitelist(array_keys($requirements))->setWhitelistDependencies($input->getOption('update-with-dependencies'));
     $status = $install->run();
     if ($status !== 0) {
         $output->writeln("\n" . '<error>Installation failed, reverting ' . $file . ' to its original content.</error>');
         file_put_contents($json->getPath(), $composerBackup);
     }
     return $status;
 }
Beispiel #13
0
 public static function determinePickle($arg, &$matches)
 {
     $versionParser = new VersionParser();
     $res = $versionParser->parseNameVersionPairs([$arg]);
     $argPrefix = substr($arg, 0, 1);
     if ($argPrefix == '/' || $argPrefix == '.') {
         return 0;
     }
     $matches = ['package' => $res[0]['name'], 'version' => isset($res[0]['version']) ? $res[0]['version'] : ''];
     return 1;
 }
Beispiel #14
0
 /**
  * {@inheritDoc}
  */
 public function findPackage($name, $version)
 {
     // normalize version & name
     $versionParser = new VersionParser();
     $version = $versionParser->normalize($version);
     $name = strtolower($name);
     foreach ($this->getPackages() as $package) {
         if ($name === $package->getName() && $version === $package->getVersion()) {
             return $package;
         }
     }
 }
Beispiel #15
0
 /**
  * Require (install) a package.
  *
  * @param array $package Package names and version to require
  *                       - Format: ['name' => '', 'version' => '']
  *
  * @throws \Bolt\Exception\PackageManagerException
  *
  * @return int 0 on success or a positive error code on failure
  */
 public function execute(array $package)
 {
     $this->getComposer();
     $io = $this->getIO();
     /** @var \Bolt\Filesystem\Handler\JsonFile $jsonFile */
     $jsonFile = $this->getOptions()->composerJson();
     $newlyCreated = !$jsonFile->exists();
     if ($newlyCreated) {
         $this->app['extend.manager.json']->update();
     }
     // Format the package array
     $package = $this->formatRequirements($package);
     // Validate requirements format
     $versionParser = new VersionParser();
     foreach ($package as $constraint) {
         $versionParser->parseConstraints($constraint);
     }
     // Get a back up of the file contents
     $composerBackup = $jsonFile->parse();
     // Update our JSON file now with a specific version.
     // This is what Composer will read, and use, internally during the process.
     // After that is complete, we'll re-save with a constraint
     $this->updateComposerJson($jsonFile, $package, false);
     // JSON file has been created/updated, if we're not installing, exit
     if ($this->getOptions()->noUpdate()) {
         return 0;
     }
     // Reload Composer config
     $composer = $this->resetComposer();
     /** @var $install \Composer\Installer */
     $install = Installer::create($io, $composer)->setVerbose($this->getOptions()->verbose())->setPreferSource($this->getOptions()->preferSource())->setPreferDist($this->getOptions()->preferDist())->setDevMode(!$this->getOptions()->updateNoDev())->setOptimizeAutoloader($this->getOptions()->optimizeAutoloader())->setClassMapAuthoritative($this->getOptions()->classmapAuthoritative())->setUpdate($this->getOptions()->update())->setUpdateWhitelist(array_keys($package))->setWhitelistDependencies($this->getOptions()->updateWithDependencies())->setIgnorePlatformRequirements($this->getOptions()->ignorePlatformReqs())->setRunScripts(!$this->getOptions()->noScripts());
     try {
         $status = $install->run();
         if ($status !== 0) {
             if ($newlyCreated) {
                 // Installation failed, deleting JSON
                 $jsonFile->delete();
             } else {
                 // Installation failed, reverting JSON to its original content
                 $jsonFile->dump($composerBackup);
             }
         }
         // Update our JSON file now with a constraint
         $this->updateComposerJson($jsonFile, $package, true);
         return $status;
     } catch (\Exception $e) {
         // Installation failed, reverting JSON to its original content
         $jsonFile->dump($composerBackup);
         $msg = sprintf('%s recieved an error from Composer: %s in %s::%s', __METHOD__, $e->getMessage(), $e->getFile(), $e->getLine());
         $this->app['logger.system']->critical($msg, ['event' => 'exception', 'exception' => $e]);
         throw new PackageManagerException($e->getMessage(), $e->getCode(), $e);
     }
 }
 public function testCheckPhpVersionFailed()
 {
     $this->composerInfo->expects($this->once())->method('getRequiredPhpVersion')->willReturn('1.0');
     $multipleConstraints = $this->getMockForAbstractClass('Composer\\Package\\LinkConstraint\\LinkConstraintInterface', [], '', false);
     $this->versionParser->expects($this->at(0))->method('parseConstraints')->willReturn($multipleConstraints);
     $this->versionParser->expects($this->at(1))->method('normalize')->willReturn('1.0');
     $currentPhpVersion = $this->getMockForAbstractClass('Composer\\Package\\LinkConstraint\\LinkConstraintInterface', [], '', false);
     $this->versionParser->expects($this->at(2))->method('parseConstraints')->willReturn($currentPhpVersion);
     $multipleConstraints->expects($this->once())->method('matches')->willReturn(false);
     $expected = ['responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, 'data' => ['required' => 1.0, 'current' => PHP_VERSION]];
     $this->assertEquals($expected, $this->phpReadinessCheck->checkPhpVersion());
 }
 /**
  * Execute the command.
  *
  * @param  InputInterface  $input
  * @param  OutputInterface $output
  * @param  bool            $inverted Whether to invert matching process (why-not vs why behaviour)
  * @return int|null        Exit code of the operation.
  */
 protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false)
 {
     // Emit command event on startup
     $composer = $this->getComposer();
     $commandEvent = new CommandEvent(PluginEvents::COMMAND, $this->getName(), $input, $output);
     $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
     // Prepare repositories and set up a pool
     $platformOverrides = $composer->getConfig()->get('platform') ?: array();
     $repository = new CompositeRepository(array(new ArrayRepository(array($composer->getPackage())), $composer->getRepositoryManager()->getLocalRepository(), new PlatformRepository(array(), $platformOverrides)));
     $pool = new Pool();
     $pool->addRepository($repository);
     // Parse package name and constraint
     list($needle, $textConstraint) = array_pad(explode(':', $input->getArgument(self::ARGUMENT_PACKAGE)), 2, $input->getArgument(self::ARGUMENT_CONSTRAINT));
     // Find packages that are or provide the requested package first
     $packages = $pool->whatProvides($needle);
     if (empty($packages)) {
         throw new \InvalidArgumentException(sprintf('Could not find package "%s" in your project', $needle));
     }
     // Include replaced packages for inverted lookups as they are then the actual starting point to consider
     $needles = array($needle);
     if ($inverted) {
         foreach ($packages as $package) {
             $needles = array_merge($needles, array_map(function (Link $link) {
                 return $link->getTarget();
             }, $package->getReplaces()));
         }
     }
     // Parse constraint if one was supplied
     if ('*' !== $textConstraint) {
         $versionParser = new VersionParser();
         $constraint = $versionParser->parseConstraints($textConstraint);
     } else {
         $constraint = null;
     }
     // Parse rendering options
     $renderTree = $input->getOption(self::OPTION_TREE);
     $recursive = $renderTree || $input->getOption(self::OPTION_RECURSIVE);
     // Resolve dependencies
     $results = $repository->getDependents($needles, $constraint, $inverted, $recursive);
     if (empty($results)) {
         $extra = null !== $constraint ? sprintf(' in versions %smatching %s', $inverted ? 'not ' : '', $textConstraint) : '';
         $this->getIO()->writeError(sprintf('<info>There is no installed package depending on "%s"%s</info>', $needle, $extra));
     } elseif ($renderTree) {
         $this->initStyles($output);
         $root = $packages[0];
         $this->getIO()->write(sprintf('<info>%s</info> %s %s', $root->getPrettyName(), $root->getPrettyVersion(), $root->getDescription()));
         $this->printTree($results);
     } else {
         $this->printTable($output, $results);
     }
     return 0;
 }
Beispiel #18
0
 public static function createComposerInMemoryPackage($targetDir, $version)
 {
     $url = self::getURL($version);
     $versionParser = new VersionParser();
     $normVersion = $versionParser->normalize($version);
     $package = new Package(self::PHANTOMJS_NAME, $normVersion, $version);
     $package->setTargetDir($targetDir);
     $package->setInstallationSource('dist');
     $package->setDistType(pathinfo($url, PATHINFO_EXTENSION) === 'zip' ? 'zip' : 'tar');
     // set zip, tarball
     $package->setDistUrl($url);
     return $package;
 }
Beispiel #19
0
 public function getPlatformRequirements($withDevReqs = false)
 {
     $lockData = $this->getLockData();
     $versionParser = new VersionParser();
     $requirements = array();
     if (!empty($lockData['platform'])) {
         $requirements = $versionParser->parseLinks('__ROOT__', '1.0.0', 'requires', isset($lockData['platform']) ? $lockData['platform'] : array());
     }
     if ($withDevReqs && !empty($lockData['platform-dev'])) {
         $devRequirements = $versionParser->parseLinks('__ROOT__', '1.0.0', 'requires', isset($lockData['platform-dev']) ? $lockData['platform-dev'] : array());
         $requirements = array_merge($requirements, $devRequirements);
     }
     return $requirements;
 }
Beispiel #20
0
 public function findPackages($name, $version = null)
 {
     $name = strtolower($name);
     if (null !== $version) {
         $versionParser = new VersionParser();
         $version = $versionParser->normalize($version);
     }
     $packages = array();
     foreach ($this->getPackages() as $package) {
         if ($package->getName() === $name && (null === $version || $version === $package->getVersion())) {
             $packages[] = $package;
         }
     }
     return $packages;
 }
Beispiel #21
0
 /**
  * finds a package by name and version if provided
  *
  * @param  RepositoryInterface        $installedRepo
  * @param  RepositoryInterface        $repos
  * @param  string                     $name
  * @param  ConstraintInterface|string $version
  * @throws \InvalidArgumentException
  * @return array                      array(CompletePackageInterface, array of versions)
  */
 protected function getPackage(RepositoryInterface $installedRepo, RepositoryInterface $repos, $name, $version = null)
 {
     $name = strtolower($name);
     $constraint = is_string($version) ? $this->versionParser->parseConstraints($version) : $version;
     $policy = new DefaultPolicy();
     $pool = new Pool('dev');
     $pool->addRepository($repos);
     $matchedPackage = null;
     $versions = array();
     $matches = $pool->whatProvides($name, $constraint);
     foreach ($matches as $index => $package) {
         // skip providers/replacers
         if ($package->getName() !== $name) {
             unset($matches[$index]);
             continue;
         }
         // select an exact match if it is in the installed repo and no specific version was required
         if (null === $version && $installedRepo->hasPackage($package)) {
             $matchedPackage = $package;
         }
         $versions[$package->getPrettyVersion()] = $package->getVersion();
         $matches[$index] = $package->getId();
     }
     // select preferred package according to policy rules
     if (!$matchedPackage && $matches && ($preferred = $policy->selectPreferredPackages($pool, array(), $matches))) {
         $matchedPackage = $pool->literalToPackage($preferred[0]);
     }
     return array($matchedPackage, $versions);
 }
 /**
  * {@inheritdoc}
  */
 public function getOutput(OperationInterface $operation, UrlGenerator $urlGenerator = null)
 {
     if (!$operation instanceof UpdateOperation) {
         throw new \LogicException('Operation should be an instance of UpdateOperation');
     }
     $output = [];
     $initialPackage = $operation->getInitialPackage();
     $targetPackage = $operation->getTargetPackage();
     $versionFrom = new Version($initialPackage->getVersion(), $initialPackage->getPrettyVersion(), method_exists($initialPackage, 'getFullPrettyVersion') ? $initialPackage->getFullPrettyVersion() : VersionParser::formatVersion($initialPackage));
     $versionTo = new Version($targetPackage->getVersion(), $targetPackage->getPrettyVersion(), method_exists($targetPackage, 'getFullPrettyVersion') ? $targetPackage->getFullPrettyVersion() : VersionParser::formatVersion($targetPackage));
     $action = 'updated';
     if (Comparator::greaterThan($versionFrom->getName(), $versionTo->getName())) {
         $action = 'downgraded';
     }
     $output[] = sprintf(' - <fg=green>%s</fg=green> %s from <fg=yellow>%s</fg=yellow> to <fg=yellow>%s</fg=yellow>', $initialPackage->getName(), $action, $versionFrom->getPretty(), $versionTo->getPretty());
     if ($urlGenerator) {
         $compareUrl = $urlGenerator->generateCompareUrl($initialPackage->getSourceUrl(), $versionFrom, $targetPackage->getSourceUrl(), $versionTo);
         if (!empty($compareUrl)) {
             $output[] = sprintf('   See changes: %s', $compareUrl);
         }
         $releaseUrl = $urlGenerator->generateReleaseUrl($this->extractSourceUrl($operation), $versionTo);
         if (!empty($releaseUrl)) {
             $output[] = sprintf('   Release notes: %s', $releaseUrl);
         }
     }
     return $output;
 }
 /**
  * @param Composer $composer
  * @param IOInterface $io
  */
 public function activate(Composer $composer, IOInterface $io)
 {
     $repositoryManager = $composer->getRepositoryManager();
     $extra = $composer->getPackage()->getExtra();
     if (!isset($extra['connect-packages'])) {
         return;
     }
     $versionParser = new VersionParser();
     $links = [];
     foreach ($extra['connect-packages'] as $connectPackage => $version) {
         try {
             $releases = $this->getVersionsForPackage($connectPackage);
         } catch (InvalidArgumentException $e) {
             $message = '<error>Could not find release manifest for module with extension key: "%s". ';
             $message .= 'Did you get the casing right? Error: "%s"</error>';
             $io->writeError(sprintf($message, $connectPackage, $e->getMessage()), true);
             continue;
         } catch (UnexpectedValueException $e) {
             $message = '<error>Non valid XML return from connect for module with extension key: "%s".</error>';
             $message .= $e->getMessage();
             $io->writeError(sprintf($message, $connectPackage), true);
             continue;
         }
         $repository = $this->addPackages($releases, $connectPackage);
         $repositoryManager->addRepository($repository);
         $constraint = $versionParser->parseConstraints($version);
         $links[] = new Link($composer->getPackage()->getName(), $connectPackage, $constraint);
     }
     if (!empty($links)) {
         $requires = $composer->getPackage()->getRequires();
         $requires = array_merge($requires, $links);
         $composer->getPackage()->setRequires($requires);
     }
 }
 public function update()
 {
     $versions = $this->packagist->getPackageVersions('silverstripe/framework');
     foreach ($versions as $package) {
         $version = $package->getVersion();
         // Replace version by branch alias if applicable
         $extra = $package->getExtra();
         if (isset($extra['branch-alias'][$version])) {
             $version = $extra['branch-alias'][$version];
         }
         $stability = VersionParser::parseStability($version);
         $isDev = $stability === 'dev';
         if (!$isDev || in_array($version, $this->versionBlacklist)) {
             continue;
         }
         $match = preg_match('/^([0-9]+)\\.([0-9]+)\\.x-dev$/', $version, $matches);
         if (!$match) {
             continue;
         }
         $major = $matches[1];
         $minor = $matches[2];
         $record = SilverStripeVersion::get()->filter('Major', $major)->filter('Minor', $minor)->first();
         if (!$record) {
             $record = new SilverStripeVersion();
             $record->Name = "{$major}.{$minor}";
             $record->Major = $major;
             $record->Minor = $minor;
             $record->write();
         }
     }
 }
 private function updateCompatibility(Addon $addon, AddonVersion $version, CompletePackage $package)
 {
     $require = null;
     if ($package->getRequire()) {
         foreach ($package->getRequire() as $name => $link) {
             if ((string) $link == 'self.version') {
                 continue;
             }
             if ($name == 'silverstripe/framework') {
                 $require = $link;
                 break;
             }
             if ($name == 'silverstripe/cms') {
                 $require = $link;
             }
         }
     }
     if (!$require) {
         return;
     }
     $addon->CompatibleVersions()->removeAll();
     $version->CompatibleVersions()->removeAll();
     foreach ($this->silverstripes as $id => $link) {
         try {
             $constraint = $this->versionParser->parseConstraints($require);
             if ($link->matches($constraint)) {
                 $addon->CompatibleVersions()->add($id);
                 $version->CompatibleVersions()->add($id);
             }
         } catch (Exception $e) {
             // An exception here shouldn't prevent further updates.
             Debug::log($addon->Name . "\t" . $addon->ID . "\t" . $e->getMessage());
         }
     }
 }
 /**
  * @dataProvider getRecommendedRequireVersionPackages
  */
 public function testFindRecommendedRequireVersion($prettyVersion, $isDev, $stability, $expectedVersion, $branchAlias = null)
 {
     $pool = $this->createMockPool();
     $versionSelector = new VersionSelector($pool);
     $versionParser = new VersionParser();
     $package = $this->getMock('\\Composer\\Package\\PackageInterface');
     $package->expects($this->any())->method('getPrettyVersion')->will($this->returnValue($prettyVersion));
     $package->expects($this->any())->method('getVersion')->will($this->returnValue($versionParser->normalize($prettyVersion)));
     $package->expects($this->any())->method('isDev')->will($this->returnValue($isDev));
     $package->expects($this->any())->method('getStability')->will($this->returnValue($stability));
     $branchAlias = $branchAlias === null ? array() : array('branch-alias' => array($prettyVersion => $branchAlias));
     $package->expects($this->any())->method('getExtra')->will($this->returnValue($branchAlias));
     $recommended = $versionSelector->findRecommendedRequireVersion($package);
     // assert that the recommended version is what we expect
     $this->assertEquals($expectedVersion, $recommended);
 }
 /**
  * All descendants' constructors should call this parent constructor
  *
  * @param PackageInterface $aliasOf       The package this package is an alias of
  * @param string           $version       The version the alias must report
  * @param string           $prettyVersion The alias's non-normalized version
  */
 public function __construct(PackageInterface $aliasOf, $version, $prettyVersion)
 {
     parent::__construct($aliasOf->getName());
     $this->version = $version;
     $this->prettyVersion = $prettyVersion;
     $this->aliasOf = $aliasOf;
     $this->stability = VersionParser::parseStability($version);
     $this->dev = $this->stability === 'dev';
     // replace self.version dependencies
     foreach (array('requires', 'devRequires') as $type) {
         $links = $aliasOf->{'get' . ucfirst($type)}();
         foreach ($links as $index => $link) {
             // link is self.version, but must be replacing also the replaced version
             if ('self.version' === $link->getPrettyConstraint()) {
                 $links[$index] = new Link($link->getSource(), $link->getTarget(), new VersionConstraint('=', $this->version), $type, $prettyVersion);
             }
         }
         $this->{$type} = $links;
     }
     // duplicate self.version provides
     foreach (array('conflicts', 'provides', 'replaces') as $type) {
         $links = $aliasOf->{'get' . ucfirst($type)}();
         $newLinks = array();
         foreach ($links as $link) {
             // link is self.version, but must be replacing also the replaced version
             if ('self.version' === $link->getPrettyConstraint()) {
                 $newLinks[] = new Link($link->getSource(), $link->getTarget(), new VersionConstraint('=', $this->version), $type, $prettyVersion);
             }
         }
         $this->{$type} = array_merge($links, $newLinks);
     }
 }
Beispiel #28
0
 /**
  * Creates a new in memory package.
  *
  * @param string $name        The package's name
  * @param string $version     The package's version
  * @param string $prettyVersion The package's non-normalized version
  */
 public function __construct($name, $version, $prettyVersion)
 {
     parent::__construct($name);
     $this->version = $version;
     $this->prettyVersion = $prettyVersion;
     $this->dev = VersionParser::isDev($version);
 }
 /**
  * Verifies php version
  *
  * @return JsonModel
  */
 public function phpVersionAction()
 {
     try {
         $requiredVersion = $this->phpInformation->getRequiredPhpVersion();
     } catch (\Exception $e) {
         return new JsonModel(['responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, 'data' => ['error' => 'phpVersionError', 'message' => 'Cannot determine required PHP version: ' . $e->getMessage()]]);
     }
     $multipleConstraints = $this->versionParser->parseConstraints($requiredVersion);
     $currentPhpVersion = new VersionConstraint('=', PHP_VERSION);
     $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS;
     if (!$multipleConstraints->matches($currentPhpVersion)) {
         $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR;
     }
     $data = ['responseType' => $responseType, 'data' => ['required' => $requiredVersion, 'current' => PHP_VERSION]];
     return new JsonModel($data);
 }
Beispiel #30
0
 public function __construct($name, $version, $prettyVersion)
 {
     parent::__construct($name);
     $this->version = $version;
     $this->prettyVersion = $prettyVersion;
     $this->stability = VersionParser::parseStability($version);
     $this->dev = $this->stability === 'dev';
 }