/**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     if ($input->post('FORM_SUBMIT') == 'tl_composer_migrate_undo') {
         /** @var RootPackage $rootPackage */
         $rootPackage = $this->composer->getPackage();
         $requires = $rootPackage->getRequires();
         foreach (array_keys($requires) as $package) {
             if ($package != 'contao-community-alliance/composer') {
                 unset($requires[$package]);
             }
         }
         $rootPackage->setRequires($requires);
         $lockPathname = preg_replace('#\\.json$#', '.lock', $this->configPathname);
         /** @var DownloadManager $downloadManager */
         $downloadManager = $this->composer->getDownloadManager();
         $downloadManager->setOutputProgress(false);
         $installer = Installer::create($this->io, $this->composer);
         if (file_exists(TL_ROOT . '/' . $lockPathname)) {
             $installer->setUpdate(true);
         }
         if ($installer->run()) {
             $_SESSION['COMPOSER_OUTPUT'] .= $this->io->getOutput();
         } else {
             $_SESSION['COMPOSER_OUTPUT'] .= $this->io->getOutput();
             $this->redirect('contao/main.php?do=composer&migrate=undo');
         }
         // load config
         $json = new JsonFile(TL_ROOT . '/' . $this->configPathname);
         $config = $json->read();
         // remove migration status
         unset($config['extra']['contao']['migrated']);
         // write config
         $json->write($config);
         // disable composer client and enable repository client
         $inactiveModules = deserialize($GLOBALS['TL_CONFIG']['inactiveModules']);
         $inactiveModules[] = '!composer';
         foreach (array('rep_base', 'rep_client', 'repository') as $module) {
             $pos = array_search($module, $inactiveModules);
             if ($pos !== false) {
                 unset($inactiveModules[$pos]);
             }
         }
         if (version_compare(VERSION, '3', '>=')) {
             $skipFile = new \File('system/modules/!composer/.skip');
             $skipFile->write('Remove this file to enable the module');
             $skipFile->close();
         }
         if (file_exists(TL_ROOT . '/system/modules/repository/.skip')) {
             $skipFile = new \File('system/modules/repository/.skip');
             $skipFile->delete();
         }
         $this->Config->update("\$GLOBALS['TL_CONFIG']['inactiveModules']", serialize($inactiveModules));
         $this->redirect('contao/main.php?do=repository_manager');
     }
     $template = new \BackendTemplate('be_composer_client_migrate_undo');
     $template->composer = $this->composer;
     $template->output = $_SESSION['COMPOSER_OUTPUT'];
     unset($_SESSION['COMPOSER_OUTPUT']);
     return $template->parse();
 }
 /**
  * {@inheritdoc}
  *
  * @SuppressWarnings(PHPMD.LongVariable)
  */
 public function handle(\Input $input)
 {
     $packageName = $input->get('install');
     if ($packageName == 'contao/core') {
         $this->redirect('contao/main.php?do=composer');
     }
     if ($input->post('version')) {
         $version = base64_decode(rawurldecode($input->post('version')));
         // make a backup
         copy(TL_ROOT . '/' . $this->configPathname, TL_ROOT . '/' . $this->configPathname . '~');
         // update requires
         $json = new JsonFile(TL_ROOT . '/' . $this->configPathname);
         $config = $json->read();
         if (!array_key_exists('require', $config)) {
             $config['require'] = array();
         }
         $config['require'][$packageName] = $version;
         ksort($config['require']);
         $json->write($config);
         Messages::addInfo(sprintf($GLOBALS['TL_LANG']['composer_client']['added_candidate'], $packageName, $version));
         $_SESSION['COMPOSER_OUTPUT'] .= $this->io->getOutput();
         $this->redirect('contao/main.php?do=composer');
     }
     $installationCandidates = $this->searchPackage($packageName);
     if (empty($installationCandidates)) {
         Messages::addError(sprintf($GLOBALS['TL_LANG']['composer_client']['noInstallationCandidates'], $packageName));
         $_SESSION['COMPOSER_OUTPUT'] .= $this->io->getOutput();
         $this->redirect('contao/main.php?do=composer');
     }
     $template = new \BackendTemplate('be_composer_client_install');
     $template->composer = $this->composer;
     $template->packageName = $packageName;
     $template->candidates = $installationCandidates;
     return $template->parse();
 }
 /**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     $removeNames = $input->post('packages') ? explode(',', $input->post('packages')) : array($input->post('remove'));
     // filter undeletable packages
     $removeNames = array_filter($removeNames, function ($removeName) {
         return !in_array($removeName, InstalledController::$UNDELETABLE_PACKAGES);
     });
     // skip empty
     if (empty($removeNames)) {
         $this->redirect('contao/main.php?do=composer');
     }
     // make a backup
     copy(TL_ROOT . '/' . $this->configPathname, TL_ROOT . '/' . $this->configPathname . '~');
     // update requires
     $json = new JsonFile(TL_ROOT . '/' . $this->configPathname);
     $config = $json->read();
     if (!array_key_exists('require', $config)) {
         $config['require'] = array();
     }
     foreach ($removeNames as $removeName) {
         unset($config['require'][$removeName]);
     }
     $json->write($config);
     $_SESSION['TL_INFO'][] = sprintf($GLOBALS['TL_LANG']['composer_client']['removeCandidate'], implode(', ', $removeNames));
     $_SESSION['COMPOSER_OUTPUT'] .= $this->io->getOutput();
     $this->redirect('contao/main.php?do=composer');
 }
Example #4
0
 /**
  * {@inheritdoc}
  *
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  * @throws \LogicException
  * @throws BadMethodCallException
  */
 public function load($resource, $type = null)
 {
     $path = $this->locator->locate($resource);
     $this->container->addResource(new FileResource($path));
     $file = new JsonFile($path);
     $content = $file->read();
     $extension = pathinfo($resource, PATHINFO_FILENAME);
     if (array_key_exists('parameters', $content)) {
         foreach ($content['parameters'] as $name => $parameter) {
             $this->container->setParameter($name, $parameter);
         }
         unset($content['parameters']);
     }
     if (array_key_exists('imports', $content)) {
         foreach ($content['imports'] as $import) {
             $importFilename = $import;
             if (!Path::isAbsolute($importFilename)) {
                 $importFilename = Path::join([dirname($path), $import]);
             }
             $this->import($importFilename, null, false, $file);
         }
         unset($content['imports']);
     }
     $this->container->loadFromExtension($extension, $content);
 }
Example #5
0
 /**
  * Set up Composer JSON file.
  *
  * @return array|null
  */
 public function updateJson()
 {
     if (!is_file($this->getOption('composerjson'))) {
         $this->initJson($this->getOption('composerjson'));
     }
     $jsonFile = new JsonFile($this->getOption('composerjson'));
     if ($jsonFile->exists()) {
         $json = $jsonorig = $jsonFile->read();
         // Workaround Bolt 2.0 installs with "require": []
         if (isset($json['require']) && empty($json['require'])) {
             unset($json['require']);
         }
         $json = $this->setJsonDefaults($json);
     } else {
         // Error
         $this->messages[] = Trans::__("The Bolt extensions file '%composerjson%' isn't readable.", ['%composerjson%' => $this->getOption('composerjson')]);
         $this->app['extend.writeable'] = false;
         $this->app['extend.online'] = false;
         return null;
     }
     // Write out the file, but only if it's actually changed, and if it's writable.
     if ($json != $jsonorig) {
         try {
             umask(00);
             $jsonFile->write($json);
         } catch (\Exception $e) {
             $this->messages[] = Trans::__('The Bolt extensions Repo at %repository% is currently unavailable. Check your connection and try again shortly.', ['%repository%' => $this->app['extend.site']]);
         }
     }
     return $json;
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $composer = $this->getComposer();
     $config = $composer->getConfig();
     $isInitDone = true;
     // Init packages.json
     $directory = $this->getRepositoryDirectory();
     $file = new JsonFile($directory . '/packages.json');
     if (!$file->exists()) {
         $output->writeln('<info>Initializing composer repository in</info> <comment>' . $directory . '</comment>');
         $file->write(array('packages' => (object) array()));
         $isInitDone = false;
     }
     // Init ~/composer/config.json
     $file = new JsonFile($this->getComposerHome() . '/config.json');
     $config = $file->exists() ? $file->read() : array();
     if (!isset($config['repositories'])) {
         $config['repositories'] = array();
     }
     $isRepoActived = false;
     foreach ($config['repositories'] as $repo) {
         if ($repo['type'] === 'composer' && $repo['url'] === 'file://' . $directory) {
             $isRepoActived = true;
         }
     }
     if (!$isRepoActived) {
         $output->writeln('<info>Writing stone repository in global configuration</info>');
         $config['repositories'][] = array('type' => 'composer', 'url' => 'file://' . $directory);
         $file->write($config);
         $isInitDone = false;
     }
     if ($isInitDone) {
         $output->writeln('<info>It seems stone is already configured</info>');
     }
 }
Example #7
0
 /**
  * @param InputInterface  $input  The input instance
  * @param OutputInterface $output The output instance
  *
  * @return int
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var FormatterHelper $formatter */
     $formatter = $this->getHelper('formatter');
     $configFile = $input->getArgument('file');
     $repositoryUrl = $input->getArgument('url');
     if (preg_match('{^https?://}i', $configFile)) {
         $output->writeln('<error>Unable to write to remote file ' . $configFile . '</error>');
         return 2;
     }
     $file = new JsonFile($configFile);
     if (!$file->exists()) {
         $output->writeln('<error>File not found: ' . $configFile . '</error>');
         return 1;
     }
     if (!$this->isRepositoryValid($repositoryUrl)) {
         $output->writeln('<error>Invalid Repository URL: ' . $repositoryUrl . '</error>');
         return 3;
     }
     $config = $file->read();
     if (!isset($config['repositories']) || !is_array($config['repositories'])) {
         $config['repositories'] = [];
     }
     foreach ($config['repositories'] as $repository) {
         if (isset($repository['url']) && $repository['url'] == $repositoryUrl) {
             $output->writeln('<error>Repository already added to the file</error>');
             return 4;
         }
     }
     $config['repositories'][] = ['type' => 'vcs', 'url' => $repositoryUrl];
     $file->write($config);
     $output->writeln(['', $formatter->formatBlock('Your configuration file successfully updated! It\'s time to rebuild your repository', 'bg=blue;fg=white', true), '']);
     return 0;
 }
Example #8
0
 protected function initialize()
 {
     parent::initialize();
     $this->io->write('Initializing PEAR repository ' . $this->url);
     $this->initializeChannel();
     $this->io->write('Packages names will be prefixed with: pear-' . $this->channel . '/');
     // try to load as a composer repo
     try {
         $json = new JsonFile($this->url . '/packages.json', new RemoteFilesystem($this->io));
         $packages = $json->read();
         if ($this->io->isVerbose()) {
             $this->io->write('Repository is Composer-compatible, loading via packages.json instead of PEAR protocol');
         }
         $loader = new ArrayLoader();
         foreach ($packages as $data) {
             foreach ($data['versions'] as $rev) {
                 if (strpos($rev['name'], 'pear-' . $this->channel) !== 0) {
                     $rev['name'] = 'pear-' . $this->channel . '/' . $rev['name'];
                 }
                 $this->addPackage($loader->load($rev));
                 if ($this->io->isVerbose()) {
                     $this->io->write('Loaded ' . $rev['name'] . ' ' . $rev['version']);
                 }
             }
         }
         return;
     } catch (\Exception $e) {
     }
     $this->fetchFromServer();
 }
Example #9
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;
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $filesystem = new Filesystem();
     $packageName = $this->getPackageFilename($name = $this->argument('name'));
     if (!($targetDir = $this->option('dir'))) {
         $targetDir = $this->container->path();
     }
     $sourcePath = $this->container->get('path.packages') . '/' . $name;
     $filesystem->ensureDirectoryExists($targetDir);
     $target = realpath($targetDir) . '/' . $packageName . '.zip';
     $filesystem->ensureDirectoryExists(dirname($target));
     $exludes = [];
     if (file_exists($composerJsonPath = $sourcePath . '/composer.json')) {
         $jsonFile = new JsonFile($composerJsonPath);
         $jsonData = $jsonFile->read();
         if (!empty($jsonData['archive']['exclude'])) {
             $exludes = $jsonData['archive']['exclude'];
         }
         if (!empty($jsonData['archive']['scripts'])) {
             system($jsonData['archive']['scripts'], $return);
             if ($return !== 0) {
                 throw new \RuntimeException('Can not executes scripts.');
             }
         }
     }
     $tempTarget = sys_get_temp_dir() . '/composer_archive' . uniqid() . '.zip';
     $filesystem->ensureDirectoryExists(dirname($tempTarget));
     $archiver = new PharArchiver();
     $archivePath = $archiver->archive($sourcePath, $tempTarget, 'zip', $exludes);
     rename($archivePath, $target);
     $filesystem->remove($tempTarget);
     return $target;
 }
 /**
  * Runs the project configurator.
  *
  * @return void
  */
 public function run()
 {
     $namespace = $this->ask('Namespace', function ($namespace) {
         return $this->validateNamespace($namespace);
     }, 'App');
     $packageName = $this->ask('Package name', function ($packageName) {
         return $this->validatePackageName($packageName);
     }, $this->suggestPackageName($namespace));
     $license = $this->ask('License', function ($license) {
         return trim($license);
     }, 'proprietary');
     $description = $this->ask('Description', function ($description) {
         return trim($description);
     }, '');
     $file = new JsonFile('./composer.json');
     $config = $file->read();
     $config['name'] = $packageName;
     $config['license'] = $license;
     $config['description'] = $description;
     $config['autoload']['psr-4'] = [$namespace . '\\' => 'src/'];
     $config['autoload-dev']['psr-4'] = [$namespace . '\\Tests\\' => 'tests/'];
     unset($config['scripts']['post-root-package-install']);
     $config['extra']['branch-alias']['dev-master'] = '1.0-dev';
     $file->write($config);
     $this->composer->setPackage(Factory::create($this->io, null, true)->getPackage());
     // reload root package
     $filesystem = new Filesystem();
     $filesystem->removeDirectory('./app/Distribution');
 }
Example #12
0
 /**
  * Writes the packages.json of the repository.
  *
  * @param array $includes List of included JSON files.
  */
 private function dumpPackagesJson($includes)
 {
     $repo = array('packages' => array(), 'includes' => $includes);
     $this->output->writeln('<info>Writing packages.json</info>');
     $repoJson = new JsonFile($this->filename);
     $repoJson->write($repo);
 }
 /**
  * @param OutputInterface $output
  * @param                 $dialog
  * @param                 $directory
  * @param                 $namespace
  * @param                 $phpunit
  */
 protected function processComposer(OutputInterface $output, $dialog, $directory, $namespace, $phpunit)
 {
     if ($dialog->ask($output, $dialog->getQuestion('Would you like to set up a composer file?', 'yes'), 'yes') == 'yes') {
         $this->getComposerApplication()->find('init')->run(new Input\ArrayInput(array('command' => 'init')), $output);
     }
     if (file_exists($directory . '/composer.json')) {
         $composerFile = new JsonFile($directory . '/composer.json');
         $composer = $composerFile->read();
         if (count($composer['require']) === 0) {
             unset($composer['require']);
         }
         if (isset($namespace) && $namespace) {
             $composer = array_merge($composer, array('autoload' => array('psr-0' => array($namespace => 'src/'))));
         }
         if (isset($phpunit) && $phpunit) {
             $phpunit = array('phpunit/phpunit' => '~3.7');
             if (isset($composer['require-dev'])) {
                 $composer['require-dev'] = array_merge($composer['require-dev'], $phpunit);
             } else {
                 $composer['require-dev'] = $phpunit;
             }
         }
         $composerFile->write($composer);
         if ($dialog->ask($output, $dialog->getQuestion('Would you like to run "composer install"?', 'yes'), 'yes') == 'yes') {
             if ($dialog->ask($output, $dialog->getQuestion('Would you like to install dev dependencies?', 'yes'), 'yes') == 'yes') {
                 $requireDev = true;
             } else {
                 $requireDev = false;
             }
             $output->writeln('Running composer install');
             $this->getComposerApplication()->run(new Input\ArrayInput(array('command' => 'install', '--dev' => $requireDev)));
         }
     }
 }
Example #14
0
 /**
  * Remove packages from the root install.
  *
  * @param  $packages array Indexed array of package names to remove
  *
  * @throws \Bolt\Exception\PackageManagerException
  *
  * @return int 0 on success or a positive error code on failure
  */
 public function execute(array $packages)
 {
     if (empty($packages)) {
         throw new PackageManagerException('No package specified for removal');
     }
     $io = $this->app['extend.manager']->getIO();
     $options = $this->app['extend.manager']->getOptions();
     $jsonFile = new JsonFile($options['composerjson']);
     $composerDefinition = $jsonFile->read();
     $composerBackup = file_get_contents($jsonFile->getPath());
     $json = new JsonConfigSource($jsonFile);
     $type = $options['dev'] ? 'require-dev' : 'require';
     // Remove packages from JSON
     foreach ($packages as $package) {
         if (isset($composerDefinition[$type][$package])) {
             $json->removeLink($type, $package);
         }
     }
     // Reload Composer config
     $composer = $this->app['extend.manager']->getFactory()->resetComposer();
     $install = Installer::create($io, $composer);
     try {
         $install->setVerbose($options['verbose'])->setDevMode(!$options['updatenodev'])->setUpdate(true)->setUpdateWhitelist($packages)->setWhitelistDependencies($options['updatewithdependencies'])->setIgnorePlatformRequirements($options['ignoreplatformreqs']);
         $status = $install->run();
         if ($status !== 0) {
             // Write out old JSON file
             file_put_contents($jsonFile->getPath(), $composerBackup);
         }
     } catch (\Exception $e) {
         $msg = __CLASS__ . '::' . __FUNCTION__ . ' recieved an error from Composer: ' . $e->getMessage() . ' in ' . $e->getFile() . '::' . $e->getLine();
         $this->app['logger.system']->critical($msg, array('event' => 'exception', 'exception' => $e));
         throw new PackageManagerException($e->getMessage(), $e->getCode(), $e);
     }
     return $status;
 }
Example #15
0
 protected function updateSatisConfig($package)
 {
     $satisConfig = $this->config->satisconfig;
     $satisUrl = $this->config->satisurl;
     if ($satisConfig) {
         $file = new JsonFile($satisConfig);
         $config = $file->read();
         if ($satisUrl) {
             if (!empty($this->vcs)) {
                 //$url = $package.'.git';
                 if (substr($package, -4) != '.git') {
                     $package .= '.git';
                 }
                 $repo = array('type' => 'vcs', 'url' => $this->vcs . ':' . $package);
             } else {
                 $url = $package . '.git';
                 $repo = array('type' => 'git', 'url' => $satisUrl . '/' . $url);
             }
         } else {
             $url = ltrim(realpath($this->config->repodir . '/' . $package . '.git'), '/');
             $repo = array('type' => 'git', 'url' => 'file:///' . $url);
         }
         $config['repositories'][] = $repo;
         $config['repositories'] = $this->deduplicate($config['repositories']);
         $file->write($config);
     }
 }
Example #16
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;
 }
Example #17
0
 /**
  * @param string   $name
  * @param string   $vendor
  * @param string   $package
  * @param string   $packageName
  * @param JsonFile $json
  *
  * @return array
  */
 private static function getDefinition($packageName, JsonFile $json)
 {
     $composerDefinition = $json->read();
     unset($composerDefinition['scripts']['post-create-project-cmd']);
     $composerDefinition['name'] = $packageName;
     return $composerDefinition;
 }
Example #18
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $dialog = $this->getHelperSet()->get('dialog');
     $whitelist = array('name', 'description', 'author', 'require');
     $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
     if (isset($options['author'])) {
         $options['authors'] = $this->formatAuthors($options['author']);
         unset($options['author']);
     }
     $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass();
     $file = new JsonFile('composer.json');
     $json = $file->encode($options);
     if ($input->isInteractive()) {
         $output->writeln(array('', $json, ''));
         if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
             $output->writeln('<error>Command aborted</error>');
             return 1;
         }
     }
     $file->write($options);
     if ($input->isInteractive()) {
         $ignoreFile = realpath('.gitignore');
         if (false === $ignoreFile) {
             $ignoreFile = realpath('.') . '/.gitignore';
         }
         if (!$this->hasVendorIgnore($ignoreFile)) {
             $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]?';
             if ($dialog->askConfirmation($output, $question, true)) {
                 $this->addVendorIgnore($ignoreFile);
             }
         }
     }
 }
Example #19
0
 /**
  * Command constructor.
  */
 public function __construct()
 {
     parent::__construct();
     $this->file = new JsonFile($this->container->basePath() . DIRECTORY_SEPARATOR . 'composer.json');
     $this->files = $this->container->make('files');
     $this->backup = $this->file->read();
     $this->json = new JsonConfigSource($this->file);
 }
Example #20
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;
 }
Example #21
0
 /**
  * Creates a Composer instance
  *
  * @param  IOInterface $io          IO instance
  * @param  mixed       $localConfig either a configuration array or a filename to read from, if null it will read from the default filename
  * @return Composer
  */
 public function createComposer(IOInterface $io, $localConfig = null)
 {
     // load Composer configuration
     if (null === $localConfig) {
         $localConfig = $this->getComposerFile();
     }
     if (is_string($localConfig)) {
         $composerFile = $localConfig;
         $file = new JsonFile($localConfig, new RemoteFilesystem($io));
         if (!$file->exists()) {
             if ($localConfig === 'composer.json') {
                 $message = 'Composer could not find a composer.json file in ' . getcwd();
             } else {
                 $message = 'Composer could not find the config file: ' . $localConfig;
             }
             $instructions = 'To initialize a project, please create a composer.json file as described in the http://getcomposer.org/ "Getting Started" section';
             throw new \InvalidArgumentException($message . PHP_EOL . $instructions);
         }
         $file->validateSchema(JsonFile::LAX_SCHEMA);
         $localConfig = $file->read();
     }
     // Configuration defaults
     $config = static::createConfig();
     $config->merge($localConfig);
     $vendorDir = $config->get('vendor-dir');
     $binDir = $config->get('bin-dir');
     // setup process timeout
     ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
     // initialize repository manager
     $rm = $this->createRepositoryManager($io, $config);
     // load default repository unless it's explicitly disabled
     $localConfig = $this->addPackagistRepository($localConfig);
     // load local repository
     $this->addLocalRepository($rm, $vendorDir);
     // load package
     $loader = new Package\Loader\RootPackageLoader($rm);
     $package = $loader->load($localConfig);
     // initialize download manager
     $dm = $this->createDownloadManager($io);
     // initialize installation manager
     $im = $this->createInstallationManager($rm, $dm, $vendorDir, $binDir, $io);
     // purge packages if they have been deleted on the filesystem
     $this->purgePackages($rm, $im);
     // initialize composer
     $composer = new Composer();
     $composer->setConfig($config);
     $composer->setPackage($package);
     $composer->setRepositoryManager($rm);
     $composer->setDownloadManager($dm);
     $composer->setInstallationManager($im);
     // init locker if possible
     if (isset($composerFile)) {
         $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION) ? substr($composerFile, 0, -4) . 'lock' : $composerFile . '.lock';
         $locker = new Package\Locker(new JsonFile($lockFile, new RemoteFilesystem($io)), $rm, md5_file($composerFile));
         $composer->setLocker($locker);
     }
     return $composer;
 }
 public function modifyComposerJson()
 {
     $configFile = new JsonFile('composer.json');
     $configJson = $configFile->read();
     $configJson = $this->addInitThemeScript($configJson);
     $configJson = $this->addChangeThemeVersionScript($configJson);
     $configJson = $this->addChangeThemeNameScript($configJson);
     $configFile->write($configJson);
 }
Example #23
0
 private function loadLicenses()
 {
     if (is_array($this->licenses)) {
         return $this->licenses;
     }
     $jsonFile = new JsonFile(__DIR__ . '/../../../res/spdx-licenses.json');
     $this->licenses = $jsonFile->read();
     return $this->licenses;
 }
 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;
 }
Example #25
0
 /**
  * @param \Notadd\Foundation\Extension\ExtensionManager           $manager
  * @param \Notadd\Foundation\Setting\Contracts\SettingsRepository $settings
  *
  * @return bool
  */
 public function fire(ExtensionManager $manager, SettingsRepository $settings)
 {
     $name = $this->input->getArgument('name');
     $extensions = $manager->getExtensionPaths();
     if (!$extensions->offsetExists($name)) {
         $this->error("Extension {$name} do not exist!");
         return false;
     }
     if (!$this->container->make(SettingsRepository::class)->get('extension.' . $name . '.installed')) {
         $this->error("Extension {$name} does not installed!");
         return false;
     }
     $extension = $extensions->get($name);
     $path = $extension;
     if (Str::contains($path, $manager->getVendorPath())) {
         $this->error("Please update extension {$name} from composer command!");
         return false;
     }
     $extensionFile = new JsonFile($path . DIRECTORY_SEPARATOR . 'composer.json');
     $extension = collect($extensionFile->read());
     if ($extension->has('autoload')) {
         $autoload = collect($extension->get('autoload'));
         $autoload->has('classmap') && collect($autoload->get('classmap'))->each(function ($value) use($path) {
             $path = str_replace($this->container->basePath() . '/', '', realpath($path . DIRECTORY_SEPARATOR . $value)) . '/';
             if (!in_array($path, $this->backup['autoload']['classmap'])) {
                 $this->backup['autoload']['classmap'][] = $path;
             }
         });
         $autoload->has('files') && collect($autoload->get('files'))->each(function ($value) use($path) {
             $path = str_replace($this->container->basePath() . '/', '', realpath($path . DIRECTORY_SEPARATOR . $value));
             if (!in_array($path, $this->backup['autoload']['files'])) {
                 $this->backup['autoload']['files'][] = $path;
             }
         });
         $autoload->has('psr-0') && collect($autoload->get('psr-0'))->each(function ($value, $key) use($path) {
             $path = str_replace($this->container->basePath() . '/', '', realpath($path . DIRECTORY_SEPARATOR . $value)) . '/';
             $this->backup['autoload']['psr-0'][$key] = $path;
         });
         $autoload->has('psr-4') && collect($autoload->get('psr-4'))->each(function ($value, $key) use($path) {
             $path = str_replace($this->container->basePath() . '/', '', realpath($path . DIRECTORY_SEPARATOR . $value)) . '/';
             $this->backup['autoload']['psr-4'][$key] = $path;
         });
         $this->json->addProperty('autoload', $this->backup['autoload']);
         $settings->set('extension.' . $name . '.autoload', json_encode($autoload->toArray()));
     }
     if ($extension->has('require')) {
         $require = collect($extension->get('require'));
         $require->each(function ($version, $name) {
             $this->backup['require'][$name] = $version;
         });
         $this->json->addProperty('require', $this->backup['require']);
         $settings->set('extension.' . $name . '.require', json_encode($require->toArray()));
     }
     $this->updateComposer(true);
     $this->info("Extension {$name} is updated!");
     return true;
 }
Example #26
0
 /**
  * Validates the config, and returns the result.
  *
  * @param string $file The path to the file
  *
  * @return array a triple containing the errors, publishable errors, and warnings
  */
 public function validate($file)
 {
     $errors = array();
     $publishErrors = array();
     $warnings = array();
     // validate json schema
     $laxValid = false;
     $valid = false;
     try {
         $json = new JsonFile($file, new RemoteFilesystem($this->io));
         $manifest = $json->read();
         $json->validateSchema(JsonFile::LAX_SCHEMA);
         $laxValid = true;
         $json->validateSchema();
         $valid = true;
     } catch (JsonValidationException $e) {
         foreach ($e->getErrors() as $message) {
             if ($laxValid) {
                 $publishErrors[] = $message;
             } else {
                 $errors[] = $message;
             }
         }
     } catch (\Exception $e) {
         $errors[] = $e->getMessage();
         return array($errors, $publishErrors, $warnings);
     }
     // validate actual data
     if (!empty($manifest['license'])) {
         $licenseValidator = new SpdxLicenseIdentifier();
         if (!$licenseValidator->validate($manifest['license'])) {
             $warnings[] = sprintf('License %s is not a valid SPDX license identifier, see http://www.spdx.org/licenses/ if you use an open license', json_encode($manifest['license']));
         }
     } else {
         $warnings[] = 'No license specified, it is recommended to do so';
     }
     if (!empty($manifest['name']) && preg_match('{[A-Z]}', $manifest['name'])) {
         $suggestName = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $manifest['name']);
         $suggestName = strtolower($suggestName);
         $warnings[] = sprintf('Name "%s" does not match the best practice (e.g. lower-cased/with-dashes). We suggest using "%s" instead. As such you will not be able to submit it to Packagist.', $manifest['name'], $suggestName);
     }
     try {
         $loader = new ValidatingArrayLoader(new ArrayLoader());
         if (!isset($manifest['version'])) {
             $manifest['version'] = '1.0.0';
         }
         if (!isset($manifest['name'])) {
             $manifest['name'] = 'dummy/dummy';
         }
         $loader->load($manifest);
     } catch (InvalidPackageException $e) {
         $errors = array_merge($errors, $e->getErrors());
     }
     $warnings = array_merge($warnings, $loader->getWarnings());
     return array($errors, $publishErrors, $warnings);
 }
Example #27
0
 public function getExtensionConfig()
 {
     $json = new JsonFile($this->getBasepath() . '/composer.json');
     if ($json->exists()) {
         $composerjson = $json->read();
         return array(strtolower($composerjson['name']) => array('name' => $this->getName(), 'json' => $composerjson));
     } else {
         return array($this->getName() => array('name' => $extension->getName(), 'json' => array()));
     }
 }
Example #28
0
 /**
  * @param InputInterface  $input  The input instance
  * @param OutputInterface $output The output instance
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $pages = 25;
     $page = 1;
     $output->writeln('<info>Beginning Google crawl</info>');
     $query = new QueryString(array('q' => 'site:drupalcode.org "composer.json" "drupal-module"'));
     $url = 'http://www.google.com/search?' . $query;
     // Load page 1
     $client = new Client();
     $crawler = $client->request('GET', $url);
     $repos = array();
     // Crawl through search pages.
     do {
         $current = $client->getHistory()->current()->getUri();
         $output->writeln('<info>Crawling:</info> ' . $current);
         // Use a CSS filter to select only the result links:
         $links = $crawler->filter('li h3 a');
         // Search the links for the domain:
         foreach ($links as $index => $link) {
             $href = $link->getAttribute('href');
             $query = QueryString::fromString(parse_url($href, PHP_URL_QUERY));
             $url = $query->get('q');
             // Match pages with composer.json in root.
             if (preg_match('/^http:\\/\\/drupalcode.org.+\\.git\\/.+\\/composer.json$/i', $url)) {
                 // Strip to git url and rewrite to drupalcode.org then store unique matches.
                 $matches = array();
                 preg_match('/^http:\\/\\/drupalcode.org.+\\.git/i', $url, $matches);
                 $repo = str_replace('http://drupalcode.org/', 'http://git.drupal.org/', $matches[0]);
                 $repos[$repo] = null;
                 $output->writeln('<info>Found:</info> ' . $repo);
             }
         }
         // Turn the page.
         $page++;
         $node = $crawler->filter('table#nav')->selectLink($page);
         if ($node->count()) {
             $crawler = $client->click($node->link());
         } else {
             break;
         }
     } while ($page < $pages);
     $path = getcwd() . '/satis.json';
     $file = new JsonFile($path);
     $data = $file->read();
     foreach ($data['repositories'] as $file_repo) {
         $repos[$file_repo['url']] = null;
     }
     $repos = array_keys($repos);
     sort($repos);
     $data['repositories'] = array();
     foreach ($repos as $repo) {
         $data['repositories'][] = array('url' => $repo, 'type' => 'vcs');
     }
     $file->write((array) $data);
 }
Example #29
0
 /**
  * @param string $path
  *
  * @return Config
  */
 public static function createConfig($path)
 {
     $config = new Config();
     // load global config
     $file = new JsonFile($path);
     if ($file->exists()) {
         $config->merge($file->read());
     }
     $config->setConfigSource(new JsonConfigSource($file));
     return $config;
 }
 /**
  * Reads auth config from given json file path and returns it.
  *
  * @param string $authFilePath
  * @return array
  * @throws \Seld\JsonLint\ParsingException
  */
 private function readAuthConfig($authFilePath)
 {
     $file = new JsonFile($authFilePath);
     if ($file->exists()) {
         $auth = $file->read();
         if (isset($auth['config']) && isset($auth['config']['basic-auth'])) {
             return $auth['config']['basic-auth'];
         }
     }
     return array();
 }