Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
SmetDenis committed Apr 12, 2022
1 parent 9dcec49 commit 3199f22
Show file tree
Hide file tree
Showing 15 changed files with 261 additions and 115 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ The library greatly extends the functionality of [Symfony/Console](https://symfo

* Improved progress bar with a new template and additional information. See [ExamplesProgressBar.php](demo/Commands/ExamplesProgressBar.php).
* Convert option values to a strict variable type. See [ExamplesOptionsStrictTypes.php](demo/Commands/ExamplesOptionsStrictTypes.php).
* New built-in styles and colors for text output. See [ExamplesOutput.php](demo/Commands/ExamplesOutput.php).
* New built-in styles and colors for text output. See [ExamplesStyles.php](demo/Commands/ExamplesStyles.php).
* A powerful alias `$this->_($messages, $level)` instead of `output->wrileln()`. See [ExamplesOutput.php](demo/Commands/ExamplesOutput.php).
* Display timing and memory usage information with `--profile` option.
* Show timestamp at the beginning of each message with `--timestamp` option.
Expand Down
79 changes: 21 additions & 58 deletions demo/Commands/ExamplesOutput.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
namespace DemoApp\Commands;

use JBZoo\Cli\CliCommand;
use JBZoo\Cli\CliHelper;
use JBZoo\Cli\Codes;
use JBZoo\Cli\Helper;
use Symfony\Component\Console\Input\InputOption;

/**
Expand All @@ -31,7 +31,8 @@ protected function configure(): void
{
$this
->setName('examples:output')
->addOption('exception', 'e', InputOption::VALUE_NONE, 'Throw exception');
->setDescription('Examples of output and error reporting')
->addOption('exception', null, InputOption::VALUE_NONE, 'Throw the exception');

parent::configure();
}
Expand All @@ -41,90 +42,52 @@ protected function configure(): void
*/
protected function executeAction(): int
{
// Any message that is output in the classic way (echo, print, print_r, ect)
// Will be caught and output at the end of the script run.
echo 'Legacy method. Message #1';
// Legacy way
echo "Any message that is output in the classic way (echo, print, print_r, ect).\n";
echo "Will be caught and output at the end of the script run.\n";


// ./my-app examples:output
$this->_('Regular message');
$this->_([
' * Several',
' * lines',
' * message'
' Several',
' lines',
' message.'
]);
$this->_(); // Break the line


// Render list of values
$this->_('Render list of values');
$this->_(Helper::renderList([
' Key' => 'Value',
' Key #2' => 123
], '-'));


/**
* Literally you can use the tags:
* - <color>Text</color>
* - <color-bold>Text</color-bold>
* - <color-under>Text</color-under>
* - <color-blink>Text</color-blink>
* - <color-bg>Text</color-bg>
*/
$this->_('Use different styles/colors to make terminal reading life easier');
$availableColors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default'];
$listOfExamples = [];
foreach ($availableColors as $color) {
$listOfExamples[$color] = implode(' ', [
"<{$color}>Regular</{$color}>",
"<{$color}-bold>Bold</{$color}-bold>",
"<{$color}-under>Underlined</{$color}-under>",
"<{$color}-bg>Background</{$color}-bg>",
"<{$color}-blink>Blink</{$color}-blink>",
]);
}
$this->_(Helper::renderList($listOfExamples, '*'));
$this->_();

// Info output
// ./my-app examples:output -v
$this->_('Verbose message #1 (-v)', Helper::VERB_V); // No label
$this->_('Verbose message #2 (-v)', Helper::VERB_INFO); // With Label
$this->_(['Verbose message #3 (-v)', 'Verbose message #3 (-v)'], Helper::VERB_INFO); // With Label, multi lines
if ($this->isInfoLevel()) {
$this->_();
}
$this->_('Verbose message #1 (-v)', CliHelper::VERB_V); // No label
$this->_('Verbose message #2 (-v)', CliHelper::VERB_INFO); // With Label
$this->isInfoLevel() && $this->_();


// Warning output
// ./my-app examples:output -vv
$this->_('Very verbose or not critical warning messages #1 (-vv)', Helper::VERB_VV); // No label
$this->_('Very verbose or not critical warning messages #2 (-vv)', Helper::VERB_WARNING); // With Label
if ($this->isWarningLevel()) {
$this->_();
}
$this->_('Very verbose or not critical warning messages #1 (-vv)', CliHelper::VERB_VV); // No label
$this->_('Very verbose or not critical warning messages #2 (-vv)', CliHelper::VERB_WARNING); // With Label
$this->isWarningLevel() && $this->_();


// Debug output
// ./my-app examples:output -vvv
$this->_('Super low-level message for developers #1 (-vvv)', Helper::VERB_VVV); // No label
$this->_('Super low-level message for developers #2 (-vvv)', Helper::VERB_DEBUG); // With Label
if ($this->isDebugLevel()) {
$this->_();
}
$this->_('Super low-level message for developers #1 (-vvv)', CliHelper::VERB_VVV); // No label
$this->_('Super low-level message for developers #2 (-vvv)', CliHelper::VERB_DEBUG); // With Label
$this->isDebugLevel() && $this->_();


// If output is hidden, we can use this method to show the message. It's like "always"
// ./my-app examples:output -q
$this->_('Show always (-q)', Helper::VERB_QUIET);
$this->_('You will see this line, even if <info>`--quiet`</info> is used.', CliHelper::VERB_QUIET);
$this->_();


// Error output (StdErr)
// ./my-app examples:output -vvv > /dev/null
$this->_('Your error message in runtime (non-stop)', Helper::VERB_ERROR);
$this->_('Your exception message in runtime (non-stop)', Helper::VERB_EXCEPTION);
$this->_('Your error message in runtime (non-stop)', CliHelper::VERB_ERROR);
$this->_('Your exception message in runtime (--mute-errors)', CliHelper::VERB_EXCEPTION);
$this->_();


Expand Down
78 changes: 78 additions & 0 deletions demo/Commands/ExamplesStyles.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

/**
* JBZoo Toolbox - Cli
*
* This file is part of the JBZoo Toolbox project.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package Cli
* @license MIT
* @copyright Copyright (C) JBZoo.com, All rights reserved.
* @link https://github.com/JBZoo/Cli
*/

declare(strict_types=1);

namespace DemoApp\Commands;

use JBZoo\Cli\CliCommand;
use JBZoo\Cli\Codes;
use JBZoo\Cli\CliHelper;

/**
* Class ExamplesStyles
*/
class ExamplesStyles extends CliCommand
{
protected function configure(): void
{
$this
->setName('examples:styles')
->setDescription('Examples of new CLI colors and styles');

parent::configure();
}

/**
* @inheritDoc
*/
protected function executeAction(): int
{
// Render list of values
$this->_('Render list of values');
$this->_(CliHelper::renderList([
' Key' => 'Value',
' Key #2' => 123
], '-'));


/**
* Literally you can use the tags:
* - <color>Text</color>
* - <color-bold>Text</color-bold>
* - <color-under>Text</color-under>
* - <color-blink>Text</color-blink>
* - <color-bg>Text</color-bg>
*/
$this->_('Use different styles/colors to make terminal reading life easier');
$availableColors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default'];
$listOfExamples = [];
foreach ($availableColors as $color) {
$listOfExamples[$color] = implode(' ', [
"<{$color}>Regular</{$color}>",
"<{$color}-bold>Bold</{$color}-bold>",
"<{$color}-under>Underlined</{$color}-under>",
"<{$color}-bg>Background</{$color}-bg>",
"<{$color}-blink>Blink</{$color}-blink>",
]);
}
$this->_(CliHelper::renderList($listOfExamples, '*'));
$this->_();

// Default success exist code is "0". Max value is 255.
// See JBZoo\Cli\Codes class for more info
return Codes::OK;
}
}
11 changes: 10 additions & 1 deletion demo/my-app
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,17 @@ namespace DemoApp;
use JBZoo\Cli\CliApplication;

// Init composer autoloader
require_once __DIR__ . '/vendor/autoload.php';
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
} else {
require_once dirname(__DIR__) . '/vendor/autoload.php';
}


// Set your application name and version.
$application = new CliApplication('My Console Application', 'v1.0.0');


// Looks at the online generator of ASCII logos
// https://patorjk.com/software/taag/#p=testall&f=Epic&t=My%20Console%20App
$application->setLogo(implode(PHP_EOL, [
Expand All @@ -39,13 +45,16 @@ $application->setLogo(implode(PHP_EOL, [
" |___/ |_| |_| ",
]));


// Scan directory to find commands.
// * It doesn't work recursively!
// * They must be inherited from the class \JBZoo\Cli\CliCommand
$application->registerCommandsByPath(__DIR__ . '/Commands', __NAMESPACE__);


// Action name by default (if there is no arguments)
$application->setDefaultCommand('list');


// Run application
$application->run();
1 change: 0 additions & 1 deletion src/CliApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

namespace JBZoo\Cli;

use Item8\Helpers\I8Helper;
use JBZoo\Event\EventManager;
use JBZoo\Utils\FS;
use Symfony\Component\Console\Application;
Expand Down
36 changes: 30 additions & 6 deletions src/CliCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
abstract class CliCommand extends Command
{
/**
* @var Helper
* @var CliHelper
* @psalm-suppress PropertyNotSetInConstructor
*/
protected $helper;
Expand Down Expand Up @@ -72,25 +72,25 @@ protected function configure(): void
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->helper = new Helper($input, $output);
$this->helper = new CliHelper($input, $output);

$exitCode = 0;
try {
$this->trigger('exec.before', [$this, $this->helper]);
\ob_start();
$exitCode = $this->executeAction();
if ($echoContent = \ob_get_clean()) {
$this->_("<yellow>Legacy Output:</yellow> " . $echoContent);
$this->showLegacyOutput($echoContent);
}
} catch (\Exception $exception) {
if ($echoContent = \ob_get_clean()) {
$this->_("<yellow>Legacy Output:</yellow> " . $echoContent);
$this->showLegacyOutput($echoContent);
}

$this->trigger('exception', [$this, $this->helper, $exception]);

if ($this->getOptBool('mute-errors')) {
$this->_($exception->getMessage(), Helper::VERB_EXCEPTION);
$this->_($exception->getMessage(), CliHelper::VERB_EXCEPTION);
} else {
$this->showProfiler();
throw $exception;
Expand All @@ -110,7 +110,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$exitCode = 0;
}

$this->_("Exit Code is \"{$exitCode}\"", Helper::VERB_DEBUG);
$this->_("Exit Code is \"{$exitCode}\"", CliHelper::VERB_DEBUG);

return $exitCode;
}
Expand Down Expand Up @@ -303,4 +303,28 @@ protected function trigger(string $eventName, array $arguments = [], ?callable $

return 0;
}

/**
* @param string|null $echoContent
* @return void
*/
private function showLegacyOutput(?string $echoContent): void
{
$echoContent = $echoContent ?: '';

$lines = \explode("\n", $echoContent);
$lines = array_map(static function ($line) {
return \rtrim($line);
}, $lines);

$lines = \array_filter($lines, static function ($line): bool {
return '' !== $line;
});

if (\count($lines) > 1) {
$this->_($lines, CliHelper::VERB_LEGACY);
} else {
$this->_($echoContent, CliHelper::VERB_LEGACY);
}
}
}
6 changes: 3 additions & 3 deletions src/CliCommandMultiProc.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ protected function executeMultiProcessAction(): int

$warningList = $this->getWarningList();
if (\count($warningList) > 0) {
$this->_(\implode("\n" . \str_repeat('-', 60) . "\n", $warningList), Helper::VERB_WARNING);
$this->_(\implode("\n" . \str_repeat('-', 60) . "\n", $warningList), CliHelper::VERB_WARNING);
}

return 0;
Expand Down Expand Up @@ -269,11 +269,11 @@ private function createSubProcess(string $procId): Process
$process = Process::fromShellCommandline(
Cli::build(\implode(' ', [
Sys::getBinary(),
Helper::getBinPath(),
CliHelper::getBinPath(),
$this->getName(),
\implode(" ", $argumentsList)
]), $options),
Helper::getRootPath(),
CliHelper::getRootPath(),
null,
null,
$this->getMaxTimeout()
Expand Down
Loading

0 comments on commit 3199f22

Please sign in to comment.