Skip to content

Commit

Permalink
update some command error handle logic
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 14, 2021
1 parent 58b0567 commit 9f6c6c3
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 40 deletions.
13 changes: 9 additions & 4 deletions src/AbstractApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Toolkit\Cli\Style;
use Toolkit\Cli\Util\LineParser;
use Toolkit\PFlag\SFlags;
use Toolkit\Stdlib\Helper\DataHelper;
use Toolkit\Stdlib\Helper\PhpHelper;
use Toolkit\Stdlib\OS;
use Toolkit\Sys\Proc\ProcessUtil;
Expand All @@ -39,7 +40,6 @@
use function header;
use function in_array;
use function is_int;
use function json_encode;
use function memory_get_usage;
use function microtime;
use function register_shutdown_function;
Expand Down Expand Up @@ -164,7 +164,10 @@ protected function init(): void
];

if (!$this->errorHandler) {
$this->errorHandler = new ErrorHandler();
$this->errorHandler = new ErrorHandler([
'rootPath' => $this->config['rootPath'],
'hideRootPath' => (bool)$this->config['hideRootPath'],
]);
}

$this->registerErrorHandle();
Expand Down Expand Up @@ -196,6 +199,8 @@ protected function initForRun(Input $input): void
$this->logf(Console::VERB_DEBUG, 'init - begin parse global options');
$this->flags->parse($input->getFlags());

// set debug to error handler
$this->errorHandler->setDebug($this->isDebug());
}

protected function prepareRun(): void
Expand Down Expand Up @@ -451,7 +456,7 @@ public function handleError(int $num, string $str, string $file, int $line): voi
public function handleException(Throwable $e): void
{
// you can log error on sub class ...
$this->errorHandler->handle($e, $this);
$this->errorHandler->handle($e);
}

/**
Expand Down Expand Up @@ -538,7 +543,7 @@ protected function startInteractiveShell(): void
}

$args = LineParser::parseIt($line);
$this->debugf('input line: %s, parsed args: %s', $line, json_encode($args));
$this->debugf('input line: %s, parsed args: %s', $line, DataHelper::toString($args));

// reload and parse args
$in->parse($args);
Expand Down
13 changes: 3 additions & 10 deletions src/AbstractHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

namespace Inhere\Console;

use Inhere\Console\Component\ErrorHandler;
use Inhere\Console\Concern\AttachApplicationTrait;
use Inhere\Console\Concern\CommandHelpTrait;
use Inhere\Console\Concern\InputOutputAwareTrait;
Expand Down Expand Up @@ -40,7 +41,6 @@
use function preg_replace;
use function sprintf;
use function ucfirst;
use function vdump;
use const PHP_EOL;
use const PHP_OS;

Expand Down Expand Up @@ -269,11 +269,6 @@ protected function initForRun(Input $input): void
$this->logf(Console::VERB_DEBUG, 'show help message by input flags: -h, --help');
$this->showHelp();
});

// old mode: options and arguments at method annotations
if ($this->compatible) {
$this->flags->setSkipOnUndefined(true);
}
}

protected function getBuiltInOptions(): array
Expand Down Expand Up @@ -306,12 +301,10 @@ public function run(array $args)
return $this->doRun($args);
} catch (Throwable $e) {
if ($this->isDetached()) {
// TODO exception handle
ErrorHandler::new()->handle($e);
} else {
// throw $e;
throw $e;
}

throw $e;
}

return -1;
Expand Down
3 changes: 2 additions & 1 deletion src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use RuntimeException;
use SplFileInfo;
use Throwable;
use Toolkit\Stdlib\Helper\DataHelper;
use function array_unshift;
use function class_exists;
use function implode;
Expand Down Expand Up @@ -271,7 +272,7 @@ public function dispatch(string $name, array $args = [])
}

$cmdId = $name;
$this->debugf('begin dispatch the input command: %s', $name);
$this->debugf('begin dispatch the input command: %s, args: %s', $name, DataHelper::toString($args));

// format is: `group action`
if (strpos($name, ' ') > 0) {
Expand Down
17 changes: 10 additions & 7 deletions src/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace Inhere\Console;

use Inhere\Console\Contract\CommandInterface;
use Inhere\Console\IO\Input;

/**
* Class Command
Expand All @@ -34,13 +35,15 @@ abstract class Command extends AbstractHandler implements CommandInterface
*/
protected $parent;

/*
* Do execute command
*/
// protected function execute($input, $output)
// {
// // something logic ...
// }
protected function initForRun(Input $input): void
{
parent::initForRun($input);

// old mode: options and arguments at method annotations
if ($this->compatible) {
$this->flags->setSkipOnUndefined(true);
}
}

protected function doRun(array $args)
{
Expand Down
99 changes: 92 additions & 7 deletions src/Component/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
use Inhere\Console\Contract\ErrorHandlerInterface;
use InvalidArgumentException;
use Throwable;
use Toolkit\Cli\Cli;
use Toolkit\Cli\Util\Highlighter;
use Toolkit\Stdlib\Obj\ObjectHelper;
use function file_get_contents;
use function get_class;
use function sprintf;
Expand All @@ -25,20 +27,55 @@
*/
class ErrorHandler implements ErrorHandlerInterface
{
/**
* @var bool
*/
protected $debug = false;

/**
* @var string
*/
protected $rootPath = '';

/**
* @var bool
*/
protected $hideRootPath = false;

/**
* @param array $config
*
* @return static
*/
public static function new(array $config = []): self
{
return new self($config);
}

/**
* Class constructor.
*
* @param array $config
*/
public function __construct(array $config = [])
{
ObjectHelper::init($this, $config);
}

/**
* @inheritdoc
*/
public function handle(Throwable $e, AbstractApplication $app): void
public function handle(Throwable $e): void
{
if ($e instanceof InvalidArgumentException) {
$app->getOutput()->error($e->getMessage());
Cli::error($e->getMessage());
return;
}

$class = get_class($e);

// open debug, throw exception
if ($app->isDebug()) {
if ($this->isDebug()) {
$tpl = <<<ERR
\n<error> Error </error> <mga>%s</mga>
Expand All @@ -60,16 +97,64 @@ public function handle(Throwable $e, AbstractApplication $app): void
$e->getTraceAsString()// \str_replace('):', '): -', $e->getTraceAsString())
);

if ($app->getParam('hideRootPath') && ($rootPath = $app->getParam('rootPath'))) {
if ($this->hideRootPath && ($rootPath = $this->rootPath)) {
$message = str_replace($rootPath, '{ROOT}', $message);
}

$app->write($message, false);
Cli::write($message, false);
return;
}

// simple output
$app->getOutput()->error($e->getMessage() ?: 'unknown error');
$app->write("\nYou can use '--debug 4' to see error details.");
Cli::error($e->getMessage() ?: 'unknown error');
Cli::write("\nYou can use '--debug 4' to see error details.");
}

/**
* @return bool
*/
public function isDebug(): bool
{
return $this->debug;
}

/**
* @param bool $debug
*/
public function setDebug(bool $debug): void
{
$this->debug = $debug;
}

/**
* @return string
*/
public function getRootPath(): string
{
return $this->rootPath;
}

/**
* @param string $rootPath
*/
public function setRootPath(string $rootPath): void
{
$this->rootPath = $rootPath;
}

/**
* @return bool
*/
public function isHideRootPath(): bool
{
return $this->hideRootPath;
}

/**
* @param bool $hideRootPath
*/
public function setHideRootPath(bool $hideRootPath): void
{
$this->hideRootPath = $hideRootPath;
}
}
7 changes: 2 additions & 5 deletions src/Contract/ErrorHandlerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

namespace Inhere\Console\Contract;

use Inhere\Console\AbstractApplication;
use Inhere\Console\Application;
use Throwable;

/**
Expand All @@ -20,8 +18,7 @@
interface ErrorHandlerInterface
{
/**
* @param Throwable $e
* @param Application|AbstractApplication $app
* @param Throwable $e
*/
public function handle(Throwable $e, AbstractApplication $app): void;
public function handle(Throwable $e): void;
}
12 changes: 7 additions & 5 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,11 @@ protected function disabledCommands(): array
* Will call it on action(sub-command) not found on the group.
*
* @param string $action
* @param array $args
*
* @return bool if return True, will stop goon render group help.
*/
protected function onNotFound(string $action): bool
protected function onNotFound(string $action, array $args): bool
{
// you can add custom logic on sub-command not found.
return false;
Expand Down Expand Up @@ -277,7 +278,7 @@ public function doRun(array $args)
// check method not exist
// - if command method not exists.
if (!method_exists($this, $method)) {
return $this->handleNotFound($name, $action);
return $this->handleNotFound($name, $action, $args);
}

// init flags for subcommand
Expand All @@ -290,7 +291,7 @@ public function doRun(array $args)
// load input definition configure
$this->configure();

$this->log(Console::VERB_DEBUG, "run subcommand '$command' - parse options", ['args' => $args]);
$this->log(Console::VERB_DEBUG, "run subcommand '$name.$command' - parse options", ['args' => $args]);

// parse subcommand flags.
if (!$fs->parse($args)) {
Expand Down Expand Up @@ -400,13 +401,14 @@ final public function execute($input, $output)
/**
* @param string $group
* @param string $action
* @param array $args
*
* @return int
*/
protected function handleNotFound(string $group, string $action): int
protected function handleNotFound(string $group, string $action, array $args): int
{
// if user custom handle not found logic.
if ($this->onNotFound($action)) {
if ($this->onNotFound($action, $args)) {
$this->debugf('user custom handle the "%s" action "%s" not found', $group, $action);
return 0;
}
Expand Down
8 changes: 7 additions & 1 deletion src/GlobalOption.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Inhere\Console;

use Toolkit\PFlag\FlagType;
use function array_merge;

/**
Expand Down Expand Up @@ -46,7 +47,12 @@ class GlobalOption
* @psalm-var array<string, string>
*/
private static $options = [
'--debug' => 'int;Setting the runtime log debug level(quiet 0 - 5 crazy);no;1',
// '--debug' => 'int;Setting the runtime log debug level(quiet 0 - 5 crazy);no;1',
'--debug' => [
'type' => FlagType::INT,
'desc' => 'Setting the runtime log debug level(quiet 0 - 5 crazy)',
'envVar' => Console::DEBUG_ENV_KEY,
],
// '--debug' => 'Setting the runtime log debug level(quiet 0 - 5 crazy)',
'--ishell' => 'bool;Run application an interactive shell environment',
// '--ishell' => 'Run application an interactive shell environment',
Expand Down

0 comments on commit 9f6c6c3

Please sign in to comment.