Since: 1.0
Author: Bernhard Schussek (bschussek@gmail.com)
Inheritance: implements Webmozart\Console\Api\Formatter\Formatter
Ejemplo n.º 1
0
 /**
  * Handles the "config <key>" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handleShow(Args $args, IO $io)
 {
     $raw = !$args->isOptionSet('parsed');
     $value = $this->manager->getConfigKey($args->getArgument('key'), null, true, $raw);
     $io->writeLine(StringUtil::formatValue($value, false));
     return 0;
 }
 public function handleDatabaseUpdate(Args $args, IO $io, Command $command)
 {
     $tool = new SchemaTool($this->app['entyMgr']);
     $tool->updateSchema($this->app['entyMgr']->getMetadataFactory()->getAllMetadata());
     $io->writeLine("<info>Database schema updated.</info>");
     return 0;
 }
 private function getResolvedProfile(Args $args, IO $io)
 {
     $profileResolver = new AutomaticProfileResolver($this->config);
     if ($io->isInteractive()) {
         $profileResolver = new InteractiveProfileResolver($this->config, $this->style, $profileResolver);
     }
     return $this->profileConfigResolver->resolve($profileResolver->resolve($args->getArgument('profile'))->name);
 }
Ejemplo n.º 4
0
 /**
  * Renders the paragraph.
  *
  * @param IO  $io          The I/O.
  * @param int $indentation The number of spaces to indent.
  */
 public function render(IO $io, $indentation = 0)
 {
     $linePrefix = str_repeat(' ', $indentation);
     $textWidth = $io->getTerminalDimensions()->getWidth() - 1 - $indentation;
     // TODO replace wordwrap() by implementation that is aware of format codes
     $text = preg_replace("~\n(?!\n)~", "\n" . $linePrefix, wordwrap($this->text, $textWidth));
     $io->write($linePrefix . rtrim($text) . "\n");
 }
Ejemplo n.º 5
0
 private function scopeFile($path, $prefix, IO $io)
 {
     $fileContent = file_get_contents($path);
     try {
         $scoppedContent = $this->scoper->addNamespacePrefix($fileContent, $prefix);
         $this->filesystem->dumpFile($path, $scoppedContent);
         $io->writeLine(sprintf('Scoping %s. . . Success', $path));
     } catch (ParsingException $exception) {
         $io->errorLine(sprintf('Scoping %s. . . Fail', $path));
     }
 }
Ejemplo n.º 6
0
 /**
  * Handles the "puli plugin --list" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handleList(Args $args, IO $io)
 {
     $pluginClasses = $this->manager->getPluginClasses();
     if (!$pluginClasses) {
         $io->writeLine('No plugin classes. Use "puli plugin --install <class>" to install a plugin class.');
         return 0;
     }
     foreach ($pluginClasses as $pluginClass) {
         $io->writeLine("<c1>{$pluginClass}</c1>");
     }
     return 0;
 }
Ejemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public function handle(Args $args, IO $io)
 {
     if ($this->processLauncher->isSupported()) {
         if (!$this->lessBinary) {
             $this->lessBinary = $this->executableFinder->find('less');
         }
         if ($this->lessBinary) {
             return $this->processLauncher->launchProcess(escapeshellcmd($this->lessBinary) . ' %path%', array('path' => $this->path), false);
         }
     }
     $io->write(file_get_contents($this->path));
     return 0;
 }
Ejemplo n.º 8
0
 /**
  * Handles the "upgrade" command.
  *
  * @param Args $args The console arguments
  * @param IO   $io   The I/O
  *
  * @return int The status code
  */
 public function handle(Args $args, IO $io)
 {
     $moduleFile = $this->moduleFileManager->getModuleFile();
     $originVersion = $moduleFile->getVersion();
     $targetVersion = $args->getArgument('version');
     if (version_compare($originVersion, $targetVersion, '=')) {
         $io->writeLine(sprintf('Your puli.json is already at version %s.', $targetVersion));
         return 0;
     }
     $this->moduleFileManager->migrate($targetVersion);
     $io->writeLine(sprintf('Migrated your puli.json from version %s to version %s.', $originVersion, $targetVersion));
     return 0;
 }
Ejemplo n.º 9
0
 /**
  * Handles the "self-update" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     $updateStrategy = new PuliStrategy();
     $updateStrategy->setStability($this->getStability($args));
     // false: disable signed releases, otherwise the updater will look for
     // a *.pubkey file for the PHAR
     $updater = new Updater(null, false);
     $updater->setStrategyObject($updateStrategy);
     if ($updater->update()) {
         $io->writeLine(sprintf('Updated from version %s to version %s.', $updater->getOldVersion(), $updater->getNewVersion()));
         return 0;
     }
     $io->writeLine(sprintf('Version %s is the latest version. No update required.', $updater->getOldVersion()));
     return 0;
 }
Ejemplo n.º 10
0
 public function handleList(Args $args, IO $io)
 {
     $table = new Table(PuliTableStyle::borderless());
     $servers = $this->serverManager->getServers();
     if ($servers->isEmpty()) {
         $io->writeLine('No servers. Use "puli server --add <name> <document-root>" to add a server.');
         return 0;
     }
     $table->setHeaderRow(array('Server Name', 'Installer', 'Location', 'URL Format'));
     foreach ($servers as $server) {
         $table->addRow(array('<u>' . $server->getName() . '</u>', $server->getInstallerName(), '<c2>' . $server->getDocumentRoot() . '</c2>', '<c1>' . $server->getUrlFormat() . '</c1>'));
     }
     $table->render($io);
     return 0;
 }
Ejemplo n.º 11
0
 /**
  * Handles the "ls" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath);
     $resources = $this->repo->find($path);
     if (!count($resources)) {
         $io->errorLine("No resources found for path {$path}");
         return 1;
     }
     foreach ($resources as $resource) {
         if ($resource instanceof BodyResource) {
             $io->writeLine($resource->getBody());
         }
     }
     return 0;
 }
Ejemplo n.º 12
0
 /**
  * Handles the "self-update" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     $updateStrategy = new GithubStrategy();
     $updateStrategy->setPackageName('puli/cli');
     $updateStrategy->setStability($this->getStability($args));
     $updateStrategy->setPharName('puli.phar');
     $updateStrategy->setCurrentLocalVersion(PuliApplicationConfig::VERSION);
     $updater = new Updater();
     $updater->setStrategyObject($updateStrategy);
     if ($updater->update()) {
         $io->writeLine(sprintf('Updated from version %s to version %s.', $updater->getOldVersion(), $updater->getNewVersion()));
     } else {
         $io->writeLine(sprintf('Version %s is the latest version. No update required.', $updater->getOldVersion()));
     }
     return 0;
 }
 /**
  * @param IO $io
  */
 protected function parseConfig(IO $io)
 {
     $configFile = __DIR__ . '/../../../etc/config.yml';
     if (file_exists($configFile) && is_file($configFile)) {
         $config = Yaml::parse(file_get_contents($configFile));
         try {
             $this->profile = Profile::fromArray($config);
         } catch (\InvalidArgumentException $e) {
             $io->errorLine("Invalid config.yml file");
             exit;
         }
     } else {
         $io->errorLine("No config.yml file");
         exit;
     }
 }
Ejemplo n.º 14
0
 public function handle(Args $args, IO $io, Command $command)
 {
     $tabular = Tabular::getInstance();
     $dom = new \DOMDocument('1.0');
     $dom->load($args->getArgument('xml'));
     $tableDom = $tabular->tabulate($dom, $args->getArgument('definition'));
     if ($args->getOption('debug')) {
         $io->writeLine($tableDom->saveXml());
     }
     $rows = $tableDom->toArray();
     $table = new Table(TableStyle::solidBorder());
     $table->setHeaderRow(array_keys(reset($rows) ?: array()));
     foreach ($rows as $row) {
         $table->addRow($row);
     }
     $table->render($io);
 }
Ejemplo n.º 15
0
 /**
  * Creates the I/O.
  *
  * @param string    $inputData The data to return from the input.
  * @param Formatter $formatter The formatter to use.
  */
 public function __construct($inputData = '', Formatter $formatter = null)
 {
     $formatter = $formatter ?: new PlainFormatter();
     $input = new Input(new StringInputStream($inputData));
     $output = new Output(new BufferedOutputStream(), $formatter);
     $errorOutput = new Output(new BufferedOutputStream(), $formatter);
     parent::__construct($input, $output, $errorOutput);
 }
Ejemplo n.º 16
0
 /**
  * Handles the "self-update" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     $updateStrategy = new GithubStrategy();
     $updateStrategy->setPackageName('puli/cli');
     $updateStrategy->setStability($this->getStability($args));
     $updateStrategy->setPharName('puli.phar');
     $updateStrategy->setCurrentLocalVersion(PuliApplicationConfig::VERSION);
     // false: disable signed releases, otherwise the updater will look for
     // a *.pubkey file for the PHAR
     $updater = new Updater(null, false);
     $updater->setStrategyObject($updateStrategy);
     if ($updater->update()) {
         $io->writeLine(sprintf('Updated from version %s to version %s.', $updater->getOldVersion(), $updater->getNewVersion()));
         return 0;
     }
     $io->writeLine(sprintf('Version %s is the latest version. No update required.', $updater->getOldVersion()));
     return 0;
 }
 public function handleShow(Args $args, IO $io)
 {
     $this->style->title('Show profile information');
     if ($io->isVerbose()) {
         $this->style->text([sprintf('// Using config file: %s', $this->config->get('config_file', '')), sprintf('// Project directory: %s', $this->config->get('project_directory', '')), sprintf('// Dancer config directory: %s', $this->config->get('dancer_directory', ''))]);
     }
     $profileNames = array_keys($this->config->getProfiles());
     if (!($profileName = $args->getArgument('name'))) {
         $profileName = $this->style->choice('Profile to show', $profileNames);
     }
     if (null === $profileName) {
         $this->style->error(sprintf('Unable to find a profile with name "%s".', $profileName));
         return 1;
     }
     $this->style->section($profileName);
     $this->renderResolvedProfile($this->config->getProfiles()[$profileName], $io->isVerbose());
     return 0;
 }
Ejemplo n.º 18
0
 /**
  * @param PostDispatchEvent $postDispatchEvent
  */
 public function onPostDispatchEvent(PostDispatchEvent $postDispatchEvent)
 {
     if ($this->postDispatchHandler) {
         call_user_func($this->postDispatchHandler, $postDispatchEvent->event(), $this->io);
     } else {
         $this->io->writeLine('<c1>' . $this->eventToString($postDispatchEvent->event()) . '</c1> success!!');
         $this->io->writeLine('');
     }
 }
Ejemplo n.º 19
0
 public function testGetVerbosityQuiet()
 {
     $input = new Input(new StringInputStream());
     $output = new Output(new BufferedOutputStream());
     $errorOutput = new Output(new BufferedOutputStream());
     $this->io = new IO($input, $output, $errorOutput);
     $this->output = new IOOutput($this->io);
     $this->io->setQuiet(true);
     $this->assertSame(OutputInterface::VERBOSITY_QUIET, $this->output->getVerbosity());
 }
Ejemplo n.º 20
0
 /**
  * handle.
  *
  * @param Args $args
  * @param IO   $io
  *
  * @return int
  */
 public function handle(Args $args, IO $io)
 {
     $configFileExist = true;
     $overwrite = is_string($args->getOption('force'));
     try {
         $this->configurationLoader->setRootDirectory($args->getOption('config'));
         $configuration = $this->configurationLoader->loadConfiguration();
     } catch (ConfigurationLoadingException $e) {
         $configFileExist = false;
     }
     if (!$configFileExist || $overwrite) {
         $configuration = ['urls' => ['google' => ['url' => 'https://www.google.fr', 'method' => 'GET', 'headers' => [], 'timeout' => 1, 'validator' => [], 'status_code' => 200, 'metric_uuid' => null, 'service_uuid' => null]], 'hogosha_portal' => ['username' => '', 'password' => '', 'base_uri' => 'http://localhost:8000/api/', 'metric_update' => false, 'incident_update' => false, 'default_failed_incident_message' => 'An error as occured, we are investigating %service_name%', 'default_resolved_incident_message' => 'The service %service_name% is back to normal']];
         // Dump configuration
         $content = $this->configurationDumper->dumpConfiguration($configuration);
         $this->filesystem->dumpFile($this->configurationLoader->getConfigurationFilepath(), $content);
         $io->writeLine('<info>Creating monitor file</info>');
     } else {
         $io->writeLine(sprintf('<info>You already have a configuration file in</info> "%s"', $this->configurationLoader->getConfigurationFilepath()));
     }
 }
Ejemplo n.º 21
0
 private function doWrite($message, $type)
 {
     switch ($type) {
         case self::OUTPUT_PLAIN:
             $this->io->write($this->io->removeFormat($message));
             break;
         case self::OUTPUT_RAW:
             $this->io->writeRaw($message);
             break;
         default:
             $this->io->write($message);
             break;
     }
 }
Ejemplo n.º 22
0
 /**
  * Creates the I/O.
  *
  * @param Input  $input       The standard input.
  * @param Output $output      The standard output.
  * @param Output $errorOutput The error output.
  */
 public function __construct(Input $input = null, Output $output = null, Output $errorOutput = null)
 {
     if (null === $input) {
         $inputStream = new StandardInputStream();
         $input = new Input($inputStream);
     }
     if (null === $output) {
         $outputStream = new StandardOutputStream();
         $formatter = $outputStream->supportsAnsi() ? new AnsiFormatter() : new PlainFormatter();
         $output = new Output($outputStream, $formatter);
     }
     if (null === $errorOutput) {
         $errorStream = new ErrorOutputStream();
         $formatter = $errorStream->supportsAnsi() ? new AnsiFormatter() : new PlainFormatter();
         $errorOutput = new Output($errorStream, $formatter);
     }
     parent::__construct($input, $output, $errorOutput);
 }
Ejemplo n.º 23
0
 private function printTrace(IO $io, Exception $exception)
 {
     $traces = $exception->getTrace();
     $cwd = getcwd() . DIRECTORY_SEPARATOR;
     $cwdLength = strlen($cwd);
     $lastTrace = array('function' => '', 'args' => array());
     if (null !== $exception->getFile()) {
         $lastTrace['file'] = $exception->getFile();
     }
     if (null !== $exception->getLine()) {
         $lastTrace['line'] = $exception->getLine();
     }
     array_unshift($traces, $lastTrace);
     $io->errorLine('<b>Exception trace:</b>');
     foreach ($traces as $trace) {
         $namespace = '';
         $class = '';
         $location = 'n/a';
         if (isset($trace['class'])) {
             if (false !== ($pos = strrpos($trace['class'], '\\'))) {
                 $namespace = substr($trace['class'], 0, $pos + 1);
                 $class = substr($trace['class'], $pos + 1);
             } else {
                 $class = $trace['class'];
             }
         }
         if (isset($trace['file'])) {
             if (0 === strpos($trace['file'], $cwd)) {
                 $location = substr($trace['file'], $cwdLength);
             } else {
                 $location = $trace['file'];
             }
         }
         // class, operator, function
         $signature = $class . (isset($trace['type']) ? $trace['type'] : '') . $trace['function'];
         $location .= ':' . (isset($trace['line']) ? $trace['line'] : 'n/a');
         $io->errorLineRaw(sprintf('  %s%s()', $namespace, $io->format('<u>' . $signature . '</u>')));
         $io->errorLineRaw(sprintf('    %s', $io->format('<c1>' . $location . '</c1>')));
     }
     $io->errorLine('');
     $io->errorLine('');
 }
Ejemplo n.º 24
0
 /**
  * Recursively prints the tree for the given resource.
  *
  * @param IO           $io       The I/O.
  * @param PuliResource $resource The printed resource.
  * @param int          $total    Collects the total number of printed resources.
  * @param string       $prefix   The prefix for all printed resources.
  */
 private function printTree(IO $io, PuliResource $resource, &$total, $prefix = '')
 {
     // The root node has an empty name
     $children = $resource->listChildren();
     $lastIndex = count($children) - 1;
     $index = 0;
     foreach ($children as $child) {
         $isLastChild = $index === $lastIndex;
         $childPrefix = $isLastChild ? self::LAST_CHILD_PREFIX : self::CHILD_PREFIX;
         $nestingPrefix = $isLastChild ? self::NESTING_CLOSED_PREFIX : self::NESTING_OPEN_PREFIX;
         $name = $child->getName() ?: '/';
         if ($child->hasChildren()) {
             $name = '<c1>' . $name . '</c1>';
         }
         $io->writeLine($prefix . $childPrefix . $name);
         $this->printTree($io, $child, $total, $prefix . $nestingPrefix);
         ++$index;
         ++$total;
     }
 }
Ejemplo n.º 25
0
 /**
  * Prints the heading for a binding type state.
  *
  * @param IO  $io        The I/O.
  * @param int $typeState The {@link BindingTypeState} constant.
  */
 private function printBindingTypeState(IO $io, $typeState)
 {
     switch ($typeState) {
         case BindingTypeState::ENABLED:
             $io->writeLine('The following binding types are currently enabled:');
             $io->writeLine('');
             return;
         case BindingTypeState::DUPLICATE:
             $io->writeLine('The following types have duplicate definitions and are disabled:');
             $io->writeLine('');
             return;
     }
 }
Ejemplo n.º 26
0
 /**
  * Prints the heading for a given package state.
  *
  * @param IO  $io           The I/O.
  * @param int $packageState The {@link PackageState} constant.
  */
 private function printPackageState(IO $io, $packageState)
 {
     switch ($packageState) {
         case PackageState::ENABLED:
             $io->writeLine('The following packages are currently enabled:');
             $io->writeLine('');
             return;
         case PackageState::NOT_FOUND:
             $io->writeLine('The following packages could not be found:');
             $io->writeLine(' (use "puli package --clean" to remove)');
             $io->writeLine('');
             return;
         case PackageState::NOT_LOADABLE:
             $io->writeLine('The following packages could not be loaded:');
             $io->writeLine('');
             return;
     }
 }
Ejemplo n.º 27
0
 /**
  * Prints the header for a binding state.
  *
  * @param IO  $io           The I/O.
  * @param int $bindingState The {@link BindingState} constant.
  */
 private function printBindingStateHeader(IO $io, $bindingState)
 {
     switch ($bindingState) {
         case BindingState::ENABLED:
             $io->writeLine('The following bindings are currently enabled:');
             $io->writeLine('');
             return;
         case BindingState::DISABLED:
             $io->writeLine('The following bindings are disabled:');
             $io->writeLine(' (use "puli bind --enable <uuid>" to enable)');
             $io->writeLine('');
             return;
         case BindingState::TYPE_NOT_FOUND:
             $io->writeLine('The types of the following bindings could not be found:');
             $io->writeLine(' (install or create their type definitions to enable)');
             $io->writeLine('');
             return;
         case BindingState::TYPE_NOT_ENABLED:
             $io->writeLine('The types of the following bindings are not enabled:');
             $io->writeLine(' (remove the duplicate type definitions to enable)');
             $io->writeLine('');
             return;
         case BindingState::INVALID:
             $io->writeLine('The following bindings have invalid parameters:');
             $io->writeLine(' (remove the binding and add again with correct parameters)');
             $io->writeLine('');
             return;
     }
 }
Ejemplo n.º 28
0
 private static function drawBorder(IO $io, array $columnLengths, $indentation, $lineChar, $crossingLChar, $crossingCChar, $crossingRChar, Style $style = null)
 {
     $line = str_repeat(' ', $indentation);
     $line .= $crossingLChar;
     for ($i = 0, $l = count($columnLengths); $i < $l; ++$i) {
         $line .= str_repeat($lineChar, $columnLengths[$i]);
         $line .= $i < $l - 1 ? $crossingCChar : $crossingRChar;
     }
     // Remove trailing space
     $line = rtrim($line);
     // Render only non-empty separators
     if ($line) {
         $io->write($io->format($line, $style) . "\n");
     }
 }
Ejemplo n.º 29
0
 public function handleInstall(Args $args, IO $io)
 {
     if ($args->isArgumentSet('server')) {
         $expr = Expr::same($args->getArgument('server'), AssetMapping::SERVER_NAME);
         $mappings = $this->assetManager->findAssetMappings($expr);
     } else {
         $mappings = $this->assetManager->getAssetMappings();
     }
     if (!$mappings) {
         $io->writeLine('Nothing to install.');
         return 0;
     }
     /** @var InstallationParams[] $paramsToInstall */
     $paramsToInstall = array();
     // Prepare and validate the installation of all matching mappings
     foreach ($mappings as $mapping) {
         $paramsToInstall[] = $this->installationManager->prepareInstallation($mapping);
     }
     foreach ($paramsToInstall as $params) {
         foreach ($params->getResources() as $resource) {
             $serverPath = rtrim($params->getDocumentRoot(), '/') . $params->getServerPathForResource($resource);
             $io->writeLine(sprintf('Installing <c1>%s</c1> into <c2>%s</c2> via <u>%s</u>...', $resource->getRepositoryPath(), trim($serverPath, '/'), $params->getInstallerDescriptor()->getName()));
             $this->installationManager->installResource($resource, $params);
         }
     }
     return 0;
 }
Ejemplo n.º 30
0
 /**
  * Prints the URL of a Puli path.
  *
  * @param string $path A Puli path.
  * @param IO     $io   The I/O.
  */
 private function printUrl($path, IO $io)
 {
     $path = Path::makeAbsolute($path, $this->currentPath);
     $io->writeLine($this->urlGenerator->generateUrl($path));
 }