Exemple #1
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $factory = new Factory();
     $file = $factory->getComposerFile();
     if (!file_exists($file)) {
         $output->writeln('<error>' . $file . ' not found.</error>');
         return 1;
     }
     if (!is_readable($file)) {
         $output->writeln('<error>' . $file . ' is not readable.</error>');
         return 1;
     }
     $dialog = $this->getHelperSet()->get('dialog');
     $json = new JsonFile($file);
     $composer = $json->read();
     $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'));
     $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
     $baseRequirements = array_key_exists($requireKey, $composer) ? $composer[$requireKey] : array();
     $requirements = $this->formatRequirements($requirements);
     if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey)) {
         foreach ($requirements as $package => $version) {
             $baseRequirements[$package] = $version;
         }
         $composer[$requireKey] = $baseRequirements;
         $json->write($composer);
     }
     $output->writeln('<info>' . $file . ' has been updated</info>');
     // Update packages
     $composer = $this->getComposer();
     $io = $this->getIO();
     $install = Installer::create($io, $composer);
     $install->setVerbose($input->getOption('verbose'))->setPreferSource($input->getOption('prefer-source'))->setDevMode($input->getOption('dev'))->setUpdate(true)->setUpdateWhitelist($requirements);
     return $install->run() ? 0 : 1;
 }
 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;
 }
Exemple #3
0
 public function doRun(InputInterface $input, OutputInterface $output)
 {
     $this->io = new ConsoleIO($input, $output, $this->getHelperSet());
     if (version_compare(PHP_VERSION, '5.3.2', '<')) {
         $this->getIO()->writeError('<warning>Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP ' . PHP_VERSION . ', upgrading is strongly recommended.</warning>');
     }
     if (defined('COMPOSER_DEV_WARNING_TIME')) {
         $commandName = '';
         if ($name = $this->getCommandName($input)) {
             try {
                 $commandName = $this->find($name)->getName();
             } catch (\InvalidArgumentException $e) {
             }
         }
         if ($commandName !== 'self-update' && $commandName !== 'selfupdate') {
             if (time() > COMPOSER_DEV_WARNING_TIME) {
                 $this->getIO()->writeError(sprintf('<warning>Warning: This development build of composer is over 30 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']));
             }
         }
     }
     if (getenv('COMPOSER_NO_INTERACTION')) {
         $input->setInteractive(false);
     }
     if ($newWorkDir = $this->getNewWorkingDir($input)) {
         $oldWorkingDir = getcwd();
         chdir($newWorkDir);
         if ($this->getIO()->isDebug() >= 4) {
             $this->getIO()->writeError('Changed CWD to ' . getcwd());
         }
     }
     $file = Factory::getComposerFile();
     if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
         if (isset($composer['scripts']) && is_array($composer['scripts'])) {
             foreach ($composer['scripts'] as $script => $dummy) {
                 if (!defined('Composer\\Script\\ScriptEvents::' . str_replace('-', '_', strtoupper($script)))) {
                     if ($this->has($script)) {
                         $this->getIO()->writeError('<warning>A script named ' . $script . ' would override a native Composer function and has been skipped</warning>');
                     } else {
                         $this->add(new Command\ScriptAliasCommand($script));
                     }
                 }
             }
         }
     }
     if ($input->hasParameterOption('--profile')) {
         $startTime = microtime(true);
         $this->io->enableDebugging($startTime);
     }
     $result = parent::doRun($input, $output);
     if (isset($oldWorkingDir)) {
         chdir($oldWorkingDir);
     }
     if (isset($startTime)) {
         $this->getIO()->writeError('<info>Memory usage: ' . round(memory_get_usage() / 1024 / 1024, 2) . 'MB (peak: ' . round(memory_get_peak_usage() / 1024 / 1024, 2) . 'MB), time: ' . round(microtime(true) - $startTime, 2) . 's');
     }
     return $result;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $packages = $input->getArgument('packages');
     $file = Factory::getComposerFile();
     $jsonFile = new JsonFile($file);
     $composer = $jsonFile->read();
     $composerBackup = file_get_contents($jsonFile->getPath());
     $json = new JsonConfigSource($jsonFile);
     $type = $input->getOption('dev') ? 'require-dev' : 'require';
     $altType = !$input->getOption('dev') ? 'require-dev' : 'require';
     $io = $this->getIO();
     if ($input->getOption('update-with-dependencies')) {
         $io->writeError('<warning>You are using the deprecated option "update-with-dependencies". This is now default behaviour. The --no-update-with-dependencies option can be used to remove a package without its dependencies.</warning>');
     }
     foreach ($packages as $package) {
         if (isset($composer[$type][$package])) {
             $json->removeLink($type, $package);
         } elseif (isset($composer[$altType][$package])) {
             $io->writeError('<warning>' . $package . ' could not be found in ' . $type . ' but it is present in ' . $altType . '</warning>');
             if ($io->isInteractive()) {
                 if ($io->askConfirmation('Do you want to remove it from ' . $altType . ' [<comment>yes</comment>]? ', true)) {
                     $json->removeLink($altType, $package);
                 }
             }
         } else {
             $io->writeError('<warning>' . $package . ' is not required in your composer.json and has not been removed</warning>');
         }
     }
     if ($input->getOption('no-update')) {
         return 0;
     }
     // Update packages
     $this->resetComposer();
     $composer = $this->getComposer(true, $input->getOption('no-plugins'));
     $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
     $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'remove', $input, $output);
     $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
     $install = Installer::create($io, $composer);
     $updateDevMode = !$input->getOption('update-no-dev');
     $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
     $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
     $install->setVerbose($input->getOption('verbose'))->setDevMode($updateDevMode)->setOptimizeAutoloader($optimize)->setClassMapAuthoritative($authoritative)->setUpdate(true)->setUpdateWhitelist($packages)->setWhitelistDependencies(!$input->getOption('no-update-with-dependencies'))->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
     $exception = null;
     try {
         $status = $install->run();
     } catch (\Exception $exception) {
         $status = 1;
     }
     if ($status !== 0) {
         $io->writeError("\n" . '<error>Removal failed, reverting ' . $file . ' to its original content.</error>');
         file_put_contents($jsonFile->getPath(), $composerBackup);
     }
     if ($exception) {
         throw $exception;
     }
     return $status;
 }
 public function postAutoloadDump(Event $event)
 {
     // This method is called twice. Run it only once.
     if (!$this->runPostAutoloadDump) {
         return;
     }
     $this->runPostAutoloadDump = false;
     $config = $this->composer->getConfig();
     $suffix = $config->get('autoloader-suffix');
     $vendorDir = $config->get('vendor-dir');
     $binDir = $config->get('bin-dir');
     $autoloadFile = $vendorDir . '/autoload.php';
     if (!file_exists($autoloadFile)) {
         throw new \RuntimeException(sprintf('Could not adjust autoloader: The file %s was not found.', $autoloadFile));
     }
     if (!$suffix && !$config->get('autoloader-suffix') && is_readable($autoloadFile)) {
         $content = file_get_contents($vendorDir . '/autoload.php');
         if (preg_match('{' . self::COMPOSER_AUTOLOADER_BASE . '([^:\\s]+)::}', $content, $match)) {
             $suffix = $match[1];
         }
     }
     $contents = file_get_contents($autoloadFile);
     $constant = '';
     $values = array('AUTOLOAD_CLASS' => var_export(self::COMPOSER_AUTOLOADER_BASE . $suffix, true));
     foreach ($values as $key => $value) {
         $this->io->write('<info>Generating ' . $this->constantPrefix . $key . ' constant</info>');
         $constant .= "if (!defined('{$this->constantPrefix}{$key}')) {\n";
         $constant .= sprintf("    define('{$this->constantPrefix}{$key}', %s);\n", $value);
         $constant .= "}\n\n";
     }
     $values = array_map(function ($value) {
         return var_export($value, true);
     }, array('BASE_DIR' => Path::makeRelative(getcwd(), $vendorDir), 'BIN_DIR' => Path::makeRelative($binDir, $vendorDir), 'FILE' => Path::makeRelative(realpath(Factory::getComposerFile()), $vendorDir)));
     foreach ($values as $key => $value) {
         $this->io->write('<info>Generating ' . $this->constantPrefix . $key . ' constant</info>');
         $constant .= "if (!defined('{$this->constantPrefix}{$key}')) {\n";
         $constant .= sprintf("    define('{$this->constantPrefix}{$key}', realpath(__DIR__ . DIRECTORY_SEPARATOR . %s));\n", $value);
         $constant .= "}\n\n";
     }
     $values = array('VENDOR_DIR' => $vendorDir);
     foreach ($values as $key => $value) {
         $this->io->write('<info>Generating ' . $this->constantPrefix . $key . ' constant</info>');
         $constant .= "if (!defined('{$this->constantPrefix}{$key}')) {\n";
         $constant .= sprintf("    define('{$this->constantPrefix}{$key}', realpath(__DIR__));\n");
         $constant .= "}\n\n";
     }
     // Regex modifiers:
     // "m": \s matches newlines
     // "D": $ matches at EOF only
     // Translation: insert before the last "return" in the file
     $contents = preg_replace('/\\n(?=return [^;]+;\\s*$)/mD', "\n" . $constant, $contents);
     file_put_contents($autoloadFile, $contents);
 }
 public function __construct(Composer $composer, IOInterface $io, $type = 'library', Filesystem $filesystem = null)
 {
     $this->composer = $composer;
     $this->config = $composer->getConfig();
     $this->io = $io;
     $this->root = realpath(dirname(Factory::getComposerFile()));
     if (!file_exists($this->root . '/config/modules.php')) {
         touch($this->root . '/config/modules.php');
         chmod($this->root . '/config/modules.php', 0775);
     }
     parent::__construct($io, $composer, $type, $filesystem);
 }
 public function perform($configs)
 {
     if (is_file(".ethna")) {
         return;
     }
     $config = array_merge(array("project" => "example", "renderer" => "smarty"), $configs);
     $config = $this->processParams($config, $config);
     $targets = array("app/action/Index.php", "app/view/Index.php", "app/Example_ActionClass.php", "app/Example_ActionForm.php", "app/Example_Controller.php", "app/Example_Error.php", "app/Example_ViewClass.php", "etc/example-ini.php", "skel/skel.action.php", "skel/skel.action_cli.php", "skel/skel.app_object.php", "skel/skel.entry_cli.php", "skel/skel.entry_www.php", "skel/skel.template.tpl", "skel/skel.view.php", "www/index.php");
     $project_class = self::camerize($config['project']);
     if ($config['renderer'] == 'twig') {
         if (file_exists("app/Example_Controller.php")) {
             $data = file_get_contents("app/Example_Controller.php");
             $data = preg_replace("/Ethna_Renderer_Smarty/", "Ethna_Renderer_Twig", $data);
             file_put_contents("app/Example_Controller.php", $data);
         }
     }
     foreach ($targets as $target) {
         if (file_exists($target)) {
             $data = file_get_contents($target);
             $data = preg_replace("/Example/", $project_class, $data);
             $data = preg_replace("/EXAMPLE/", strtoupper($project_class), $data);
             file_put_contents($target, $data);
             $name = basename($target);
             if (preg_match("/Example/", $name)) {
                 $name = preg_replace("/Example/", $project_class, $name);
                 $dir = dirname($target);
                 rename($target, $dir . DIRECTORY_SEPARATOR . $name);
             } else {
                 if (preg_match("/example-ini.php/", $name)) {
                     $dir = dirname($target);
                     $name = preg_replace("/example/", $config['project'], $name);
                     rename($target, $dir . DIRECTORY_SEPARATOR . $name);
                 }
             }
         }
     }
     file_put_contents(".ethna", sprintf("[project]\ncontroller_file = '%s'\ncontroller_class = '%s'", "app/{$project_class}_Controller.php", "{$project_class}_Controller"));
     if ($config['renderer'] == 'twig') {
         $file = Factory::getComposerFile();
         $prior_json = $composer_json = json_decode(file_get_contents($file), true);
         if (!isset($composer_json['require']['twig/twig'])) {
             $composer_json['require']['twig/twig'] = '1.*';
             file_put_contents($file, json_encode($composer_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
             $composer = $this->composer = Factory::create($this->io, null, true);
             $composer->getDownloadManager()->setOutputProgress(true);
             $install = Installer::create($this->io, $composer);
             $install->setVerbose(true)->setPreferSource(true)->setPreferDist(false)->setDevMode(true)->setUpdate(true)->setUpdateWhitelist(array_keys($prior_json['require']));
             // とりあえず
             $status = $install->run();
         }
     }
 }
 public static function postCreate(Event $event)
 {
     $fs = new Util\Filesystem();
     $file = Factory::getComposerFile();
     $json = new Json\JsonFile($file);
     $contents = self::unsetJsonNodes($json, static::$jsonNodes);
     $contents = self::manipulateJsonContents($contents, static::$jsonContents);
     file_put_contents($json->getPath(), $contents);
     $projectDir = realpath(".");
     self::deleteFiles($fs, $projectDir, self::$deleteFiles);
     $installersDir = dirname(realpath(__FILE__));
     $fs->remove($installersDir);
 }
 public function setup()
 {
     $this->response = null;
     $this->cleanup();
     $this->io = $this->prophesize('Composer\\IO\\IOInterface');
     $composerDefinition = new ReflectionProperty(OptionalPackages::class, 'composerDefinition');
     $composerDefinition->setAccessible(true);
     // Get composer.json
     $composerFile = Factory::getComposerFile();
     $json = new JsonFile($composerFile);
     $composerDefinition->setValue($json->read());
     $this->projectRoot = realpath(dirname($composerFile));
     $config = new ReflectionProperty(OptionalPackages::class, 'config');
     $config->setAccessible(true);
     $config->setValue(require 'src/ExpressiveInstaller/config.php');
 }
 private function checkComposerSchema()
 {
     $validator = new ConfigValidator($this->getIO());
     list($errors, $publishErrors, $warnings) = $validator->validate(Factory::getComposerFile());
     if ($errors || $publishErrors || $warnings) {
         $messages = array('error' => array_merge($errors, $publishErrors), 'warning' => $warnings);
         $output = '';
         foreach ($messages as $style => $msgs) {
             foreach ($msgs as $msg) {
                 $output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
             }
         }
         return rtrim($output);
     }
     return true;
 }
Exemple #11
0
 public static function initialize(Event $event)
 {
     $io = $event->getIO();
     $project_dirname = basename(getcwd());
     $current_namespace = self::camelize($project_dirname);
     $io->write("Initialize {$current_namespace} ...");
     $targets = self::globRecursive('app/*.php');
     $targets = array_merge($targets, self::globRecursive('app/*.html.twig'));
     $targets = array_merge($targets, self::globRecursive('tests/*.php'));
     $targets[] = 'composer.json';
     $targets[] = 'webroot/index.php';
     foreach ($targets as $target) {
         $source_text = file_get_contents($target);
         $new_source = str_replace(self::PLACEHOLDER, $current_namespace, $source_text);
         file_put_contents($target, $new_source);
     }
     copy('app/config/config_development.php.sample', 'app/config/config_development.php');
     chmod('tmp', 0777);
     // dumpautoload
     $composer = $event->getComposer();
     $gen = $composer->getAutoloadGenerator();
     $gen->setDevMode(true);
     // rename "autoload"
     $package = $composer->getPackage();
     $autoload = $package->getAutoload();
     $autoload['psr-4'][$current_namespace . '\\'] = $autoload['psr-4'][self::PLACEHOLDER . '\\'];
     unset($autoload['psr-4'][self::PLACEHOLDER . '\\']);
     unset($autoload['psr-4']['DietcubeInstaller\\']);
     $package->setAutoload($autoload);
     // rewrite json file
     $json = new JsonFile(Factory::getComposerFile());
     $composer_definition = $json->read();
     unset($composer_definition['autoload']['psr-4']['DietcubeInstaller\\']);
     unset($composer_definition['scripts']);
     $json->write($composer_definition);
     $gen->dump($composer->getConfig(), $composer->getRepositoryManager()->getLocalRepository(), $package, $composer->getInstallationManager(), 'composer', false);
     $io->write('-------------------------------------------------------------------------');
     $io->write('');
     $io->write('<comment>Dietcube setup completed.</comment>');
     $io->write('');
     $io->write('Try now with built-in server:');
     $io->write("\$ cd {$project_dirname}");
     $io->write('$ DIET_ENV=development php -d variables_order=EGPCS -S 0:8999 -t webroot/');
     $io->write('');
     $io->write('-------------------------------------------------------------------------');
     self::removeMe();
 }
 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;
     }
     $dialog = $this->getHelperSet()->get('dialog');
     $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';
     $baseRequirements = array_key_exists($requireKey, $composer) ? $composer[$requireKey] : array();
     $requirements = $this->formatRequirements($requirements);
     if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey)) {
         foreach ($requirements as $package => $version) {
             $baseRequirements[$package] = $version;
         }
         $composer[$requireKey] = $baseRequirements;
         $json->write($composer);
     }
     $output->writeln('<info>' . $file . ' has been updated</info>');
     if ($input->getOption('no-update')) {
         return 0;
     }
     // Update packages
     $composer = $this->getComposer();
     $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
     $io = $this->getIO();
     $install = Installer::create($io, $composer);
     $install->setVerbose($input->getOption('verbose'))->setPreferSource($input->getOption('prefer-source'))->setPreferDist($input->getOption('prefer-dist'))->setDevMode(true)->setUpdate(true)->setUpdateWhitelist(array_keys($requirements));
     if (!$install->run()) {
         $output->writeln("\n" . '<error>Installation failed, reverting ' . $file . ' to its original content.</error>');
         file_put_contents($json->getPath(), $composerBackup);
         return 1;
     }
     return 0;
 }
Exemple #13
0
 public static function init(Event $event)
 {
     $io = $event->getIO();
     $basePath = realpath(__DIR__ . '/../') . '/';
     // Iterate through `$keys` and get the answers
     foreach (static::$keys as $key) {
         $question = 'What is the ' . str_replace('_', ' ', $key) . '?';
         static::$answers[$key] = self::ask($io, $question, 'Larabros');
     }
     self::recursiveJob($basePath, self::rename());
     file_put_contents($basePath . 'composer.json', file_get_contents($basePath . 'composer.json.stub'));
     $json = new JsonFile(Factory::getComposerFile());
     $composerDefinition = self::getDefinition(static::$answers[':vendor_ns'] . '/' . static::$answers[':package_ns'], $json);
     // self::$packageName  = [$vendorClass, $packageClass];
     // Update composer definition
     $json->write($composerDefinition);
     $io->write("<info>composer.json is created.\n</info>");
 }
Exemple #14
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $packages = $input->getArgument('packages');
     $file = Factory::getComposerFile();
     $jsonFile = new JsonFile($file);
     $composer = $jsonFile->read();
     $composerBackup = file_get_contents($jsonFile->getPath());
     $json = new JsonConfigSource($jsonFile);
     $type = $input->getOption('dev') ? 'require-dev' : 'require';
     $altType = !$input->getOption('dev') ? 'require-dev' : 'require';
     foreach ($packages as $package) {
         if (isset($composer[$type][$package])) {
             $json->removeLink($type, $package);
         } elseif (isset($composer[$altType][$package])) {
             $this->getIO()->writeError('<warning>' . $package . ' could not be found in ' . $type . ' but it is present in ' . $altType . '</warning>');
             $dialog = $this->getHelperSet()->get('dialog');
             if ($this->getIO()->isInteractive()) {
                 if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to remove it from ' . $altType, 'yes', '?'), true)) {
                     $json->removeLink($altType, $package);
                 }
             }
         } else {
             $this->getIO()->writeError('<warning>' . $package . ' is not required in your composer.json and has not been removed</warning>');
         }
     }
     if ($input->getOption('no-update')) {
         return 0;
     }
     // Update packages
     $composer = $this->getComposer();
     $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
     $io = $this->getIO();
     $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'remove', $input, $output);
     $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
     $install = Installer::create($io, $composer);
     $updateDevMode = !$input->getOption('update-no-dev');
     $install->setVerbose($input->getOption('verbose'))->setDevMode($updateDevMode)->setUpdate(true)->setUpdateWhitelist($packages)->setWhitelistDependencies($input->getOption('update-with-dependencies'))->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'));
     $status = $install->run();
     if ($status !== 0) {
         $this->getIO()->writeError("\n" . '<error>Removal failed, reverting ' . $file . ' to its original content.</error>');
         file_put_contents($jsonFile->getPath(), $composerBackup);
     }
     return $status;
 }
Exemple #15
0
 protected static function getOptions(Event $event)
 {
     $options = array_merge(array('symfony-app-dir' => 'app', 'symfony-web-dir' => 'web'), $event->getComposer()->getPackage()->getExtra());
     $options['symfony-assets-install'] = getenv('SYMFONY_ASSETS_INSTALL') ?: @$options['symfony-assets-install'];
     if (!$options['symfony-assets-install']) {
         $options['symfony-assets-install'] = 'symlink';
     }
     $options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');
     $options['vendor-dir'] = $event->getComposer()->getConfig()->get('vendor-dir');
     $composerJsonFile = realpath(\Composer\Factory::getComposerFile());
     $rootDir = dirname($composerJsonFile);
     $options['root-dir'] = $rootDir;
     $options['app-dir-full'] = $rootDir . DIRECTORY_SEPARATOR . $options['symfony-app-dir'];
     $options['web-dir-full'] = $rootDir . DIRECTORY_SEPARATOR . $options['symfony-web-dir'];
     if ('/' == substr($options['vendor-dir'], 0, 1) || ':' == substr($options['vendor-dir'], 1, 1)) {
         $options['vendor-dir-full'] = $options['vendor-dir'];
     } else {
         $options['vendor-dir-full'] = $rootDir . DIRECTORY_SEPARATOR . $options['vendor-dir'];
     }
     return $options;
 }
 protected function setup()
 {
     // Set config
     $this->refConfig = new ReflectionProperty(OptionalPackages::class, 'config');
     $this->refConfig->setAccessible(true);
     $this->refConfig->setValue(require 'src/ExpressiveInstaller/config.php');
     $this->io = $this->prophesize('Composer\\IO\\IOInterface');
     // Set composer.json
     $composerFile = Factory::getComposerFile();
     $json = new JsonFile($composerFile);
     $localConfig = $json->read();
     $this->refComposerDefinition = new ReflectionProperty(OptionalPackages::class, 'composerDefinition');
     $this->refComposerDefinition->setAccessible(true);
     $this->refComposerDefinition->setValue($localConfig);
     // Load parsed package data
     $manager = $this->prophesize(RepositoryManager::class);
     $composerConfig = new Config();
     $composerConfig->merge(['repositories' => ['packagist' => false]]);
     $loader = new RootPackageLoader($manager->reveal(), $composerConfig);
     $package = $loader->load($localConfig);
     // Set package data
     $this->refComposerRequires = new ReflectionProperty(OptionalPackages::class, 'composerRequires');
     $this->refComposerRequires->setAccessible(true);
     $this->refComposerRequires->setValue($package->getRequires());
     $this->refComposerDevRequires = new ReflectionProperty(OptionalPackages::class, 'composerDevRequires');
     $this->refComposerDevRequires->setAccessible(true);
     $this->refComposerDevRequires->setValue($package->getDevRequires());
     $this->refStabilityFlags = new ReflectionProperty(OptionalPackages::class, 'stabilityFlags');
     $this->refStabilityFlags->setAccessible(true);
     $this->refStabilityFlags->setValue($package->getStabilityFlags());
     // Set project root
     $this->refProjectRoot = new ReflectionProperty(OptionalPackages::class, 'projectRoot');
     $this->refProjectRoot->setAccessible(true);
     $this->refProjectRoot->setValue(realpath(dirname($composerFile)));
     // Cleanup old install files
     $this->cleanup();
 }
 /**
  * Merge Drupal dependencies from extensions.
  *
  * @param \Composer\Composer $composer
  *   The Composer object.
  */
 protected function mergeForDrupalRootPackage(Composer $composer)
 {
     if ($this->state->isFirstInstall()) {
         return;
     }
     $package = $composer->getPackage();
     // Determine whether the package is a Drupal project.
     if ($package->getName() == 'drupal/drupal' && $package->getType() == 'project') {
         // @todo: There has to be a better way to get the root directory.
         $root_dir = realpath(dirname(Factory::getComposerFile()));
         // Perform the merge.
         $finder = new ComposerFinder();
         $unmanaged_extensions = $finder->getUnmanagedComposerExtensions($root_dir, $composer);
         $extensions = [];
         foreach ($unmanaged_extensions as $unmanaged_extension) {
             $extensions[] = $unmanaged_extension->getName();
         }
         $this->mergeExtensionDependenciesForRoot($root_dir, $composer);
         return;
     }
     $this->logger->debug('merge rejected for: ' . $package->getName());
 }
 /**
  * @param \Composer\IO\IOInterface $io
  * @param \Composer\Config $composerConfig
  * @return Config
  * @throws \RuntimeException
  * @throws \InvalidArgumentException
  */
 public static function load(\Composer\IO\IOInterface $io, \Composer\Config $composerConfig)
 {
     static $config;
     if ($config === null) {
         $baseDir = realpath(substr($composerConfig->get('vendor-dir'), 0, -strlen($composerConfig->get('vendor-dir', Config::RELATIVE_PATHS))));
         $localConfig = \Composer\Factory::getComposerFile();
         $file = new \Composer\Json\JsonFile($localConfig, new \Composer\Util\RemoteFilesystem($io));
         $config = new static($baseDir);
         $config->merge($file->read());
     }
     return $config;
 }
 public function storeVendorDir(Event $event)
 {
     $this->storeConstant($event, 'BARTFEENSTRA_COMPOSER_PACKAGE_LOCATOR_VENDOR_DIR', $event->getComposer()->getConfig()->get('vendor-dir'));
     $this->storeConstant($event, 'BARTFEENSTRA_COMPOSER_PACKAGE_LOCATOR_HOME_FILE', $event->getComposer()->getConfig()->get('home') . '/' . Factory::getComposerFile());
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = Factory::getComposerFile();
     $io = $this->getIO();
     $newlyCreated = !file_exists($file);
     if (!file_exists($file) && !file_put_contents($file, "{\n}\n")) {
         $io->writeError('<error>' . $file . ' could not be created.</error>');
         return 1;
     }
     if (!is_readable($file)) {
         $io->writeError('<error>' . $file . ' is not readable.</error>');
         return 1;
     }
     if (!is_writable($file)) {
         $io->writeError('<error>' . $file . ' is not writable.</error>');
         return 1;
     }
     if (filesize($file) === 0) {
         file_put_contents($file, "{\n}\n");
     }
     $json = new JsonFile($file);
     $composerDefinition = $json->read();
     $composerBackup = file_get_contents($json->getPath());
     $composer = $this->getComposer(true, $input->getOption('no-plugins'));
     $repos = $composer->getRepositoryManager()->getRepositories();
     $platformOverrides = $composer->getConfig()->get('platform') ?: array();
     // initialize $this->repos as it is used by the parent InitCommand
     $this->repos = new CompositeRepository(array_merge(array(new PlatformRepository(array(), $platformOverrides)), $repos));
     $phpVersion = $this->repos->findPackage('php', '*')->getVersion();
     $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion);
     $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
     $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
     $baseRequirements = array_key_exists($requireKey, $composerDefinition) ? $composerDefinition[$requireKey] : array();
     $requirements = $this->formatRequirements($requirements);
     // validate requirements format
     $versionParser = new VersionParser();
     foreach ($requirements as $constraint) {
         $versionParser->parseConstraints($constraint);
     }
     $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
     if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey, $removeKey, $sortPackages)) {
         foreach ($requirements as $package => $version) {
             $baseRequirements[$package] = $version;
             if (isset($composerDefinition[$removeKey][$package])) {
                 unset($composerDefinition[$removeKey][$package]);
             }
         }
         $composerDefinition[$requireKey] = $baseRequirements;
         $json->write($composerDefinition);
     }
     $io->writeError('<info>' . $file . ' has been ' . ($newlyCreated ? 'created' : 'updated') . '</info>');
     if ($input->getOption('no-update')) {
         return 0;
     }
     $updateDevMode = !$input->getOption('update-no-dev');
     $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
     $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
     // Update packages
     $this->resetComposer();
     $composer = $this->getComposer(true, $input->getOption('no-plugins'));
     $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
     $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)->setOptimizeAutoloader($optimize)->setClassMapAuthoritative($authoritative)->setUpdate(true)->setUpdateWhitelist(array_keys($requirements))->setWhitelistDependencies($input->getOption('update-with-dependencies'))->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))->setPreferStable($input->getOption('prefer-stable'))->setPreferLowest($input->getOption('prefer-lowest'));
     $exception = null;
     try {
         $status = $install->run();
     } catch (\Exception $exception) {
         $status = 1;
     }
     if ($status !== 0) {
         if ($newlyCreated) {
             $io->writeError("\n" . '<error>Installation failed, deleting ' . $file . '.</error>');
             unlink($json->getPath());
         } else {
             $io->writeError("\n" . '<error>Installation failed, reverting ' . $file . ' to its original content.</error>');
             file_put_contents($json->getPath(), $composerBackup);
         }
     }
     if ($exception) {
         throw $exception;
     }
     return $status;
 }
 /**
  * Install command: choose packages and provide configuration.
  *
  * Prompts users for package selections, and copies in package-specific
  * configuration when known.
  *
  * Updates the composer.json with the package selections, and removes the
  * install and update commands on completion.
  *
  * @param Event $event
  */
 public static function install(Event $event)
 {
     $io = $event->getIO();
     $composer = $event->getComposer();
     // Get composer.json
     $composerFile = Factory::getComposerFile();
     $json = new JsonFile($composerFile);
     self::$composerDefinition = $json->read();
     $projectRoot = realpath(dirname($composerFile));
     $io->write("<info>Setup data and cache dir</info>");
     if (!is_dir($projectRoot . '/data/cache')) {
         mkdir($projectRoot . '/data/cache', 0775, true);
         chmod($projectRoot . '/data', 0775);
     }
     $io->write("<info>Setting up optional packages</info>");
     // Get root package
     $rootPackage = $composer->getPackage();
     while ($rootPackage instanceof AliasPackage) {
         $rootPackage = $rootPackage->getAliasOf();
     }
     // Get required packages
     self::$composerRequires = $rootPackage->getRequires();
     self::$composerDevRequires = $rootPackage->getDevRequires();
     // Get stability flags
     self::$stabilityFlags = $rootPackage->getStabilityFlags();
     // Minimal?
     $minimal = self::requestMinimal($io);
     $copyFilesKey = $minimal ? 'minimal-files' : 'copy-files';
     self::$config = (require __DIR__ . '/config.php');
     foreach (self::$config['questions'] as $questionName => $question) {
         $defaultOption = isset($question['default']) ? $question['default'] : 1;
         if (isset(self::$composerDefinition['extra']['optional-packages'][$questionName])) {
             // Skip question, it's already answered
             continue;
         }
         // Get answer
         $answer = self::askQuestion($composer, $io, $question, $defaultOption);
         // Save user selected option
         self::$composerDefinition['extra']['optional-packages'][$questionName] = $answer;
         if (is_numeric($answer)) {
             // Add packages to install
             if (isset($question['options'][$answer]['packages'])) {
                 foreach ($question['options'][$answer]['packages'] as $packageName) {
                     self::addPackage($io, $packageName, self::$config['packages'][$packageName]);
                 }
             }
             // Copy files
             if (isset($question['options'][$answer][$copyFilesKey])) {
                 foreach ($question['options'][$answer][$copyFilesKey] as $source => $target) {
                     self::copyFile($io, $projectRoot, $source, $target);
                 }
             }
         } elseif ($question['custom-package'] === true && preg_match(self::PACKAGE_REGEX, $answer, $match)) {
             self::addPackage($io, $match['name'], $match['version']);
             if (isset($question['custom-package-warning'])) {
                 $io->write(sprintf("  <warning>%s</warning>", $question['custom-package-warning']));
             }
         }
         // Update composer definition
         $json->write(self::$composerDefinition);
     }
     // Set required packages
     $rootPackage->setRequires(self::$composerRequires);
     $rootPackage->setDevRequires(self::$composerDevRequires);
     // Set stability flags
     $rootPackage->setStabilityFlags(self::$stabilityFlags);
     // House keeping
     $io->write("<info>Remove installer</info>");
     // Remove composer source
     unset(self::$composerDefinition['require-dev']['composer/composer']);
     // Remove installer data
     unset(self::$composerDefinition['extra']['optional-packages']);
     if (empty(self::$composerDefinition['extra'])) {
         unset(self::$composerDefinition['extra']);
     }
     // Remove installer scripts, only need to do this once
     unset(self::$composerDefinition['scripts']['pre-update-cmd']);
     unset(self::$composerDefinition['scripts']['pre-install-cmd']);
     if (empty(self::$composerDefinition['scripts'])) {
         unset(self::$composerDefinition['scripts']);
     }
     // Remove installer script autoloading rules
     unset(self::$composerDefinition['autoload']['psr-4']['ExpressiveInstaller\\']);
     // Update composer definition
     $json->write(self::$composerDefinition);
     // Minimal install? Remove default middleware
     if ($minimal) {
         self::removeDefaultMiddleware($io, $projectRoot);
     }
     self::cleanUp($io);
 }
 /**
  * Load composer and the composer class loader.
  */
 protected function loadComposer()
 {
     // search for composer build version
     $composerDevWarningTime = Runtime::readComposerDevWarningTime();
     $incompatibleVersion = false === $composerDevWarningTime || mktime(11, 0, 0, 6, 5, 2014) > $composerDevWarningTime - 30 * 86400;
     // Update if allowed or composer version is incompatible.
     if ($incompatibleVersion || $GLOBALS['TL_CONFIG']['composerAutoUpdateLibrary'] && time() > $composerDevWarningTime) {
         Runtime::updateComposer();
         Messages::addConfirmation($GLOBALS['TL_LANG']['composer_client']['composerUpdated']);
     }
     if ($composerDevWarningTime && !$GLOBALS['TL_CONFIG']['composerAutoUpdateLibrary'] && $incompatibleVersion) {
         Messages::addError($GLOBALS['TL_LANG']['composer_client']['composerUpdateNecessary']);
     }
     // register composer class loader
     Runtime::registerComposerClassLoader();
     // define pathname to config file
     $this->configPathname = COMPOSER_DIR_RELATIVE . '/' . Factory::getComposerFile();
     // create io interface
     $this->io = new BufferIO('', $this->getDebugLevel(), new HtmlOutputFormatter());
     // create composer
     $this->composer = Runtime::createComposer($this->io);
 }
Exemple #23
0
 /**
  * {@inheritDoc}
  */
 public function doRun(InputInterface $input, OutputInterface $output)
 {
     $this->disablePluginsByDefault = $input->hasParameterOption('--no-plugins');
     $io = $this->io = new ConsoleIO($input, $output, $this->getHelperSet());
     ErrorHandler::register($io);
     // switch working dir
     if ($newWorkDir = $this->getNewWorkingDir($input)) {
         $oldWorkingDir = getcwd();
         chdir($newWorkDir);
         $io->writeError('Changed CWD to ' . getcwd(), true, IOInterface::DEBUG);
     }
     // determine command name to be executed without including plugin commands
     $commandName = '';
     if ($name = $this->getCommandName($input)) {
         try {
             $commandName = $this->find($name)->getName();
         } catch (\InvalidArgumentException $e) {
         }
     }
     if (!$this->disablePluginsByDefault && !$this->hasPluginCommands && 'global' !== $commandName) {
         try {
             foreach ($this->getPluginCommands() as $command) {
                 if ($this->has($command->getName())) {
                     $io->writeError('<warning>Plugin command ' . $command->getName() . ' (' . get_class($command) . ') would override a Composer command and has been skipped</warning>');
                 } else {
                     $this->add($command);
                 }
             }
         } catch (NoSslException $e) {
             // suppress these as they are not relevant at this point
         }
         $this->hasPluginCommands = true;
     }
     // determine command name to be executed incl plugin commands, and check if it's a proxy command
     $isProxyCommand = false;
     if ($name = $this->getCommandName($input)) {
         try {
             $command = $this->find($name);
             $commandName = $command->getName();
             $isProxyCommand = $command instanceof Command\BaseCommand && $command->isProxyCommand();
         } catch (\InvalidArgumentException $e) {
         }
     }
     if (!$isProxyCommand) {
         $io->writeError(sprintf('Running %s (%s) with %s on %s', Composer::VERSION, Composer::RELEASE_DATE, defined('HHVM_VERSION') ? 'HHVM ' . HHVM_VERSION : 'PHP ' . PHP_VERSION, php_uname('s') . ' / ' . php_uname('r')), true, IOInterface::DEBUG);
         if (PHP_VERSION_ID < 50302) {
             $io->writeError('<warning>Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP ' . PHP_VERSION . ', upgrading is strongly recommended.</warning>');
         }
         if (extension_loaded('xdebug') && !getenv('COMPOSER_DISABLE_XDEBUG_WARN')) {
             $io->writeError('<warning>You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug</warning>');
         }
         if (defined('COMPOSER_DEV_WARNING_TIME') && $commandName !== 'self-update' && $commandName !== 'selfupdate' && time() > COMPOSER_DEV_WARNING_TIME) {
             $io->writeError(sprintf('<warning>Warning: This development build of composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']));
         }
         if (getenv('COMPOSER_NO_INTERACTION')) {
             $input->setInteractive(false);
         }
         if (!Platform::isWindows() && function_exists('exec') && !getenv('COMPOSER_ALLOW_SUPERUSER')) {
             if (function_exists('posix_getuid') && posix_getuid() === 0) {
                 if ($commandName !== 'self-update' && $commandName !== 'selfupdate') {
                     $io->writeError('<warning>Do not run Composer as root/super user! See https://getcomposer.org/root for details</warning>');
                 }
                 if ($uid = (int) getenv('SUDO_UID')) {
                     // Silently clobber any sudo credentials on the invoking user to avoid privilege escalations later on
                     // ref. https://github.com/composer/composer/issues/5119
                     Silencer::call('exec', "sudo -u \\#{$uid} sudo -K > /dev/null 2>&1");
                 }
             }
             // Silently clobber any remaining sudo leases on the current user as well to avoid privilege escalations
             Silencer::call('exec', 'sudo -K > /dev/null 2>&1');
         }
         // Check system temp folder for usability as it can cause weird runtime issues otherwise
         Silencer::call(function () use($io) {
             $tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime());
             if (!(file_put_contents($tempfile, __FILE__) && file_get_contents($tempfile) == __FILE__ && unlink($tempfile) && !file_exists($tempfile))) {
                 $io->writeError(sprintf('<error>PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini</error>', sys_get_temp_dir()));
             }
         });
         // add non-standard scripts as own commands
         $file = Factory::getComposerFile();
         if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
             if (isset($composer['scripts']) && is_array($composer['scripts'])) {
                 foreach ($composer['scripts'] as $script => $dummy) {
                     if (!defined('Composer\\Script\\ScriptEvents::' . str_replace('-', '_', strtoupper($script)))) {
                         if ($this->has($script)) {
                             $io->writeError('<warning>A script named ' . $script . ' would override a Composer command and has been skipped</warning>');
                         } else {
                             $this->add(new Command\ScriptAliasCommand($script));
                         }
                     }
                 }
             }
         }
     }
     try {
         if ($input->hasParameterOption('--profile')) {
             $startTime = microtime(true);
             $this->io->enableDebugging($startTime);
         }
         $result = parent::doRun($input, $output);
         if (isset($oldWorkingDir)) {
             chdir($oldWorkingDir);
         }
         if (isset($startTime)) {
             $io->writeError('<info>Memory usage: ' . round(memory_get_usage() / 1024 / 1024, 2) . 'MB (peak: ' . round(memory_get_peak_usage() / 1024 / 1024, 2) . 'MB), time: ' . round(microtime(true) - $startTime, 2) . 's');
         }
         restore_error_handler();
         return $result;
     } catch (ScriptExecutionException $e) {
         return $e->getCode();
     } catch (\Exception $e) {
         $this->hintCommonErrors($e);
         restore_error_handler();
         throw $e;
     }
 }
Exemple #24
0
 /**
  *
  * @param array $extra
  * @param \Composer\IO\IOInterface $io
  * @return int
  */
 private function updateJsonExtra($extra, $io)
 {
     $file = Factory::getComposerFile();
     if (!file_exists($file) && !file_put_contents($file, "{\n}\n")) {
         $io->write('<error>' . $file . ' could not be created.</error>');
         return 1;
     }
     if (!is_readable($file)) {
         $io->write('<error>' . $file . ' is not readable.</error>');
         return 1;
     }
     if (!is_writable($file)) {
         $io->write('<error>' . $file . ' is not writable.</error>');
         return 1;
     }
     $json = new JsonFile($file);
     $composer = $json->read();
     $composerBackup = file_get_contents($json->getPath());
     $extraKey = 'extra';
     $baseExtra = array_key_exists($extraKey, $composer) ? $composer[$extraKey] : array();
     if (!$this->updateFileCleanly($json, $baseExtra, $extra, $extraKey)) {
         foreach ($extra as $key => $value) {
             $baseExtra[$key] = $value;
         }
         $composer[$extraKey] = $baseExtra;
         $json->write($composer);
     }
 }
Exemple #25
0
 /**
  * {@inheritDoc}
  */
 public function doRun(InputInterface $input, OutputInterface $output)
 {
     $io = $this->io = new ConsoleIO($input, $output, $this->getHelperSet());
     ErrorHandler::register($io);
     // determine command name to be executed
     $commandName = '';
     if ($name = $this->getCommandName($input)) {
         try {
             $commandName = $this->find($name)->getName();
         } catch (\InvalidArgumentException $e) {
         }
     }
     if ($commandName !== 'global') {
         if (PHP_VERSION_ID < 50302) {
             $io->writeError('<warning>Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP ' . PHP_VERSION . ', upgrading is strongly recommended.</warning>');
         }
         if (extension_loaded('xdebug') && !getenv('COMPOSER_DISABLE_XDEBUG_WARN')) {
             $io->writeError('<warning>You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug</warning>');
         }
         if (defined('COMPOSER_DEV_WARNING_TIME') && $commandName !== 'self-update' && $commandName !== 'selfupdate' && time() > COMPOSER_DEV_WARNING_TIME) {
             $io->writeError(sprintf('<warning>Warning: This development build of composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']));
         }
         if (getenv('COMPOSER_NO_INTERACTION')) {
             $input->setInteractive(false);
         }
         // switch working dir
         if ($newWorkDir = $this->getNewWorkingDir($input)) {
             $oldWorkingDir = getcwd();
             chdir($newWorkDir);
             $io->writeError('Changed CWD to ' . getcwd(), true, IOInterface::DEBUG);
         }
         // add non-standard scripts as own commands
         $file = Factory::getComposerFile();
         if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
             if (isset($composer['scripts']) && is_array($composer['scripts'])) {
                 foreach ($composer['scripts'] as $script => $dummy) {
                     if (!defined('Composer\\Script\\ScriptEvents::' . str_replace('-', '_', strtoupper($script)))) {
                         if ($this->has($script)) {
                             $io->writeError('<warning>A script named ' . $script . ' would override a native Composer function and has been skipped</warning>');
                         } else {
                             $this->add(new Command\ScriptAliasCommand($script));
                         }
                     }
                 }
             }
         }
     }
     try {
         if ($input->hasParameterOption('--profile')) {
             $startTime = microtime(true);
             $this->io->enableDebugging($startTime);
         }
         $result = parent::doRun($input, $output);
         if (isset($oldWorkingDir)) {
             chdir($oldWorkingDir);
         }
         if (isset($startTime)) {
             $io->writeError('<info>Memory usage: ' . round(memory_get_usage() / 1024 / 1024, 2) . 'MB (peak: ' . round(memory_get_peak_usage() / 1024 / 1024, 2) . 'MB), time: ' . round(microtime(true) - $startTime, 2) . 's');
         }
         return $result;
     } catch (\Exception $e) {
         $this->hintCommonErrors($e);
         throw $e;
     }
 }
 private function createConfig()
 {
     $config = Factory::createConfig();
     $file = new JsonFile(Factory::getComposerFile());
     if (!$file->exists()) {
         return $config;
     }
     $file->validateSchema(JsonFile::LAX_SCHEMA);
     $config->merge($file->read());
     return $config;
 }
 /**
  * @return string The current composer.lock absolute path
  */
 protected static function getComposerFile()
 {
     return Factory::getComposerFile();
 }
 /**
  * Install command: choose packages and provide configuration.
  *
  * Prompts users for package selections, and copies in package-specific
  * configuration when known.
  *
  * Updates the composer.json with the package selections, and removes the
  * install and update commands on completion.
  *
  * @param Event $event
  *
  * @codeCoverageIgnore
  */
 public static function install(Event $event)
 {
     $io = $event->getIO();
     $composer = $event->getComposer();
     // Get composer.json
     $composerFile = Factory::getComposerFile();
     $json = new JsonFile($composerFile);
     self::$composerDefinition = $json->read();
     self::$projectRoot = realpath(dirname($composerFile));
     $io->write("<info>Setup data and cache dir</info>");
     if (!is_dir(self::$projectRoot . '/data/cache')) {
         mkdir(self::$projectRoot . '/data/cache', 0775, true);
         chmod(self::$projectRoot . '/data', 0775);
     }
     $io->write("<info>Setting up optional packages</info>");
     // Get root package
     $rootPackage = $composer->getPackage();
     while ($rootPackage instanceof AliasPackage) {
         $rootPackage = $rootPackage->getAliasOf();
     }
     // Get required packages
     self::$composerRequires = $rootPackage->getRequires();
     self::$composerDevRequires = $rootPackage->getDevRequires();
     // Get stability flags
     self::$stabilityFlags = $rootPackage->getStabilityFlags();
     // Cleanup development dependencies
     self::removeDevDependencies();
     // Minimal?
     $minimal = self::requestMinimal($io);
     $copyFilesKey = $minimal ? 'minimal-files' : 'copy-files';
     self::$config = (require __DIR__ . '/config.php');
     foreach (self::$config['questions'] as $questionName => $question) {
         $defaultOption = isset($question['default']) ? $question['default'] : 1;
         if (isset(self::$composerDefinition['extra']['optional-packages'][$questionName])) {
             // Skip question, it's already answered
             continue;
         }
         // Get answer
         $answer = self::askQuestion($composer, $io, $question, $defaultOption);
         // Process answer
         self::processAnswer($io, $question, $answer, $copyFilesKey);
         // Save user selected option
         self::$composerDefinition['extra']['optional-packages'][$questionName] = $answer;
         // Update composer definition
         $json->write(self::$composerDefinition);
     }
     // Set required packages
     $rootPackage->setRequires(self::$composerRequires);
     $rootPackage->setDevRequires(self::$composerDevRequires);
     // Set stability flags
     $rootPackage->setStabilityFlags(self::$stabilityFlags);
     // House keeping
     $io->write("<info>Remove installer</info>");
     self::removeInstallerFromDefinition();
     // Update composer definition
     $json->write(self::$composerDefinition);
     // Minimal install? Remove default middleware
     if ($minimal) {
         self::removeDefaultMiddleware($io, self::$projectRoot);
     }
     self::clearComposerLockFile($io, self::$projectRoot);
     self::cleanUp($io, self::$projectRoot);
 }
Exemple #29
0
 private function getMinimumStability(InputInterface $input)
 {
     if ($input->hasOption('stability')) {
         return $input->getOption('stability') ?: 'stable';
     }
     $file = Factory::getComposerFile();
     if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
         if (!empty($composer['minimum-stability'])) {
             return $composer['minimum-stability'];
         }
     }
     return 'stable';
 }
 /**
  * @throws \Exception
  */
 protected function updateExtraJson()
 {
     $composerFile = Factory::getComposerFile();
     if (!file_exists($composerFile) && !file_put_contents($composerFile, "{\n}\n")) {
         throw new Exception(sprintf('%s could not be created', $composerFile));
     }
     if (!is_readable($composerFile)) {
         throw new Exception(sprintf('%s is not readable', $composerFile));
     }
     if (!is_writable($composerFile)) {
         throw new Exception(sprintf('%s is not writable', $composerFile));
     }
     $json = new JsonFile($composerFile);
     $composer = $json->read();
     $baseExtra = array_key_exists(self::EXTRA_KEY, $composer) ? $composer[self::EXTRA_KEY] : array();
     if (!$this->updateFileCleanly($json, $baseExtra, $this->extra, self::EXTRA_KEY)) {
         foreach ($this->extra as $key => $value) {
             $baseExtra[$key] = $value;
         }
         $composer[self::EXTRA_KEY] = $baseExtra;
         $json->write($composer);
     }
 }