php-shell/lib/Shell.php

599 lines
18 KiB
PHP
Raw Normal View History

2016-04-13 01:19:22 +00:00
<?php
namespace NoccyLabs\Shell;
use NoccyLabs\Shell\LineRead;
use NoccyLabs\TinyEvent\EventEmitterTrait;
use NoccyLabs\TinyEvent\Event;
2016-04-13 01:19:22 +00:00
2016-11-01 14:12:11 +00:00
class Shell
2016-04-13 01:19:22 +00:00
{
use EventEmitterTrait;
const EVT_UPDATE_PROMPT = "shell.prompt"; // called to update the prompt
const EVT_BEFORE_COMMAND = "shell.command.before"; // before a command is executed
const EVT_AFTER_COMMAND = "shell.command.after"; // after a command is executed
const EVT_BAD_COMMAND = "shell.command.bad"; // no such command found
const EVT_CONTEXT_CHANGED = "shell.context"; // a new context is activated
const EVT_SHELL_START = "shell.start"; // the shell is about to start
const EVT_SHELL_STOP = "shell.stop"; // the shell is about to exit
const EVT_SHELL_ABORT = "shell.abort"; // the shell was aborted (ctrl-c)
const EVT_SHELL_ESCAPE = "shell.escape"; // escape key pressed
const EVT_TASK_CREATED = "task.created"; // a task was created
const EVT_TASK_DESTROYED = "task.destryed"; // a task was removed or invalidated
/**
* @var LineRead The lineread instance
*/
2016-11-01 14:12:11 +00:00
protected $lineReader = null;
/**
* @var Context The current context
*/
2016-11-01 14:12:11 +00:00
protected $context = null;
/**
* @var Context[] The stack of parent contexts
*/
2016-11-01 14:12:11 +00:00
protected $contextStack = [];
2017-01-23 23:49:13 +00:00
/**
* @var object[] Created timers
*/
2016-11-02 13:22:53 +00:00
protected $timers = [];
/**
* @var TaskInterface[] Created tasks
2017-01-23 23:49:13 +00:00
*/
protected $tasks = [];
2017-01-23 23:49:13 +00:00
/**
* @var string The prompt string
*/
protected $prompt = ">";
2017-01-23 23:49:13 +00:00
/**
* @var Style The style applied to the prompt
*/
protected $prompt_style = null;
2017-01-23 23:49:13 +00:00
/**
* @var Style The style applied to the input text
*/
protected $input_style = null;
/**
* @var callable The callback to pass the input on to
*/
protected $input_callback = null;
/**
* @var string Question prompt for getInput()
*/
protected $input_prompt = null;
/**
* @var string The prompt before changing to $input_prompt
*/
protected $input_last_prompt = null;
2016-11-01 14:12:11 +00:00
2017-01-23 23:49:13 +00:00
/**
* Constructor
*
*/
public function __construct()
{
2017-01-23 23:49:13 +00:00
$t = $this;
register_shutdown_function(function () use (&$t) {
if ($t) unset($t);
});
}
/**
* Destructor
*
*/
public function __destruct()
{
if ($this->lineReader) {
$this->lineReader = null;
}
2016-11-01 14:12:11 +00:00
}
2016-04-13 01:19:22 +00:00
2017-01-28 12:00:26 +00:00
/**
* Return the current context
*
* @return Context The current context
*/
public function getContext()
{
return $this->context;
}
2016-11-01 14:12:11 +00:00
/**
* Push a new primary context, saving the previous contexts on a stack.
*
* @param Context $context
*/
public function pushContext(Context $context)
2016-04-13 01:19:22 +00:00
{
2016-11-01 14:12:11 +00:00
if ($this->context) {
$context->setParent($this->context);
2016-11-01 14:12:11 +00:00
array_unshift($this->contextStack, $this->context);
2016-04-25 18:47:30 +00:00
}
$context->setShell($this);
2016-11-01 14:12:11 +00:00
$this->context = $context;
$this->dispatchEvent(self::EVT_CONTEXT_CHANGED);
2016-04-13 01:19:22 +00:00
}
2016-11-01 14:12:11 +00:00
/**
* Pop the current context.
*
* @return Context
*/
public function popContext()
2016-04-13 01:19:22 +00:00
{
2016-11-01 14:12:11 +00:00
$previous = $this->context;
if (count($this->contextStack)>0) {
$this->context = array_shift($this->contextStack);
} else {
$this->context = null;
2016-04-25 18:47:30 +00:00
}
$this->dispatchEvent(self::EVT_CONTEXT_CHANGED);
2016-11-01 14:12:11 +00:00
return $previous;
}
2016-04-25 18:47:30 +00:00
2016-11-01 14:12:11 +00:00
public function getContextPath($separator=":")
{
2016-11-01 14:32:53 +00:00
// Return null if we don't have a current context
if (!$this->context)
return null;
// Assemble the contexts to walk
2016-11-01 14:12:11 +00:00
$stack = [ $this->context->getName() ];
foreach ($this->contextStack as $context) {
$stack[] = $context->getName();
2016-04-13 01:19:22 +00:00
}
2016-11-01 14:32:53 +00:00
// Reverse the order to make it more logical
2016-11-01 14:12:11 +00:00
$stack = array_reverse($stack);
return join($separator,$stack);
2016-04-13 01:19:22 +00:00
}
2016-11-01 14:12:11 +00:00
/**
* Create a new empty context and push it on the stack.
2016-11-01 14:12:11 +00:00
*
* @param string $name The name of the context to create
* @return Context The created context
2016-11-01 14:12:11 +00:00
*/
public function createContext($name)
2016-11-01 14:12:11 +00:00
{
$context = new Context($name);
$this->pushContext($context);
return $context;
2016-04-13 01:19:22 +00:00
}
2016-11-01 14:12:11 +00:00
/**
* Add a callback to be called at a regular interval during the update phase.
* Adding timers with a low interval (less than 200 i.e. 0.2s) may have an
* impact on performance.
*
* @param int $interval Interval in ms
* @param callable $handler The handler
* @param array $userdata Data to be passed to the handler
* @return Timer
*/
public function addTimer($interval, callable $handler, array $userdata=[])
2016-04-13 01:19:22 +00:00
{
2016-11-02 13:22:53 +00:00
$timer = new class($interval, $handler, $userdata) {
private $next;
private $interval;
private $handler;
private $userdata;
public function __construct($interval, callable $handler, array $userdata) {
$this->interval = $interval / 1000;
2017-01-22 22:22:13 +00:00
$this->next = microtime(true) + $this->interval;
2016-11-02 13:22:53 +00:00
$this->handler = $handler;
$this->userdata = $userdata;
}
public function update() {
$now = microtime(true);
if ($now > $this->next) {
$this->next = $now + $this->interval;
call_user_func($this->handler, $this->userdata);
}
}
};
$this->timers[] = $timer;
return $timer;
2016-04-13 01:19:22 +00:00
}
2016-11-01 14:12:11 +00:00
/**
* Remove a created timer.
*
* @param Timer $timer
*/
2017-01-22 22:22:13 +00:00
public function removeTimer($timer)
2016-04-13 01:19:22 +00:00
{
2017-01-22 22:22:13 +00:00
$this->timers = array_filter($this->timers, function ($v) use ($timer) {
return ($v !== $timer);
});
2016-04-13 01:19:22 +00:00
}
/**
* Add a task to be update():d in the main loop.
*
* @param TaskInterface $task The task to add
*/
public function addTask(TaskInterface $task)
{
if ($this->dispatchEvent(self::EVT_TASK_CREATED, [
'task' => $task
])->isPropagationStopped()) {
return;
}
$this->tasks[] = $task;
}
/**
* Remove a previously added task. This can also be done by the task returning
* false from its isValid() method.
*
* @param TaskInterface $task The task to remove
*/
public function removeTask(TaskInterface $task)
{
$this->tasks = array_filter($this->tasks, function ($item) use ($task) {
return ($item != $task);
});
$this->dispatchEvent(self::EVT_TASK_DESTROYED, [
'task' => $task
]);
}
2017-01-23 23:49:13 +00:00
/**
* Set the prompt text
*
* @param string $text The text
*/
2016-11-01 14:12:11 +00:00
public function setPrompt($text)
2016-04-29 13:49:10 +00:00
{
$this->prompt = $text;
if ($this->lineReader) {
$this->lineReader->setPromptText($text);
2016-11-01 14:12:11 +00:00
}
2016-04-29 13:49:10 +00:00
}
2017-01-23 23:49:13 +00:00
/**
* Set the prompt style
*
* @param Style $style The style to apply to the prompt
*/
public function setPromptStyle(Style $style)
{
$this->prompt_style = $style;
if ($this->lineReader) {
$this->lineReader->setPromptStyle($style);
}
}
2017-01-23 23:49:13 +00:00
/**
* Set the input style
*
* @param Style $style The style to apply to the text
*/
public function setInputStyle(Style $style)
{
$this->input_style = $style;
if ($this->lineReader) {
$this->lineReader->setCommandStyle($style);
}
}
2016-11-01 14:12:11 +00:00
/**
* Find a command and return a closure.
*
* @return callable The command
*/
private function findCommand($command)
{
2016-11-01 14:12:11 +00:00
// Go over current context and walk through stack until finding command
if ($this->context->hasCommand($command)) {
$handler = $this->context->getCommand($command);
} else {
foreach($this->contextStack as $context) {
if ($context->hasCommand($command) && $context->isCommandGlobal($command)) {
$handler = $context->getCommand($command);
break;
}
2016-11-01 14:12:11 +00:00
}
}
// No handler...
2016-11-01 14:12:11 +00:00
if (empty($handler)) {
return false;
}
// Return closure
return function (...$args) use ($handler) {
return call_user_func($handler, ...$args);
};
}
2016-11-01 14:12:11 +00:00
/**
* Execute a command with arguments.
*
* @param string $command The command name to execute
2017-01-23 23:49:13 +00:00
* @param string ...$args Arguments
2016-11-01 14:12:11 +00:00
* @return mixed
* @throws Exception\BadCommandExcception
*/
public function executeCommand($command, ...$args)
{
if ($this->dispatchEvent(self::EVT_BEFORE_COMMAND, [
'command' => $command,
'args' => $args
])->isPropagationStopped()) {
return true;
}
2016-11-01 14:12:11 +00:00
if ($this->executeBuiltin($command, ...$args)) {
$this->dispatchEvent(self::EVT_AFTER_COMMAND, [
'command' => $command,
'args' => $args,
'type' => 'builtin'
]);
2016-11-01 14:12:11 +00:00
return;
}
// Call the handler if the command was found
if (($target = $this->findCommand($command))) {
$ret = $target(...$args);
if ($ret instanceof Context) {
$this->pushContext($ret);
}
$this->dispatchEvent(self::EVT_AFTER_COMMAND, [
'command' => $command,
'args' => $args,
'type' => 'command'
]);
2016-11-01 14:12:11 +00:00
return;
}
// Call 'execute' on the current context
if ($this->context->execute($command, ...$args)) {
$this->dispatchEvent(self::EVT_AFTER_COMMAND, [
'command' => $command,
'args' => $args,
'type' => 'execute'
]);
return;
}
// Fire the EVT_BAD_COMMAND event and return if the event propagation
// has been stopped.
$evt = $this->dispatchEvent(self::EVT_BAD_COMMAND, [
'command'=>$command,
'args'=>$args
]);
if ($evt->isPropagationStopped()) {
return;
}
2016-11-01 14:12:11 +00:00
// Throw error if the command could not be found
throw new Exception\BadCommandException("Command {$command} not found");
}
2017-01-23 23:49:13 +00:00
/**
* Execute a built-in command
*
* @param string $command Command name
* @param mixed ...$args Arguments
* @return bool True if the command was handled OK
*/
2016-11-01 14:12:11 +00:00
public function executeBuiltin($command, ...$args)
{
switch ($command) {
case '.':
2016-11-01 15:27:23 +00:00
$type = basename(strtr(get_class($this->context), "\\", "/"));
2016-11-15 02:29:00 +00:00
printf("%s<%s>: %s\n", $type, $this->context->getName(), $this->context->getContextInfo());
$level = 0;
foreach ($this->contextStack as $context) {
2016-11-01 15:27:23 +00:00
$type = basename(strtr(get_class($context), "\\", "/"));
2016-11-15 02:29:00 +00:00
printf(" %s└─%s<%s>: %s\n", str_repeat(" ",$level++), $type, $context->getName(), $context->getContextInfo());
}
2016-11-01 14:12:11 +00:00
break;
case '..':
if (count($this->contextStack)>0)
$this->popContext();
break;
case 'help':
2016-11-01 15:10:35 +00:00
$help = $this->context->getCommandHelp();
$ghelp = [];
foreach ($this->contextStack as $context) {
$commands = $context->getCommandHelp();
foreach ($commands as $command=>$info) {
if (strpos(" ",$command)!==false) {
list ($cmd,$arg)=explode(" ",$command,2);
} else {
$cmd = $command;
}
if ($context->isCommandGlobal($cmd)) {
$ghelp[$command] = $info;
}
}
}
ksort($ghelp);
2017-01-27 03:36:23 +00:00
$_ = function($command,$args,$info) {
2017-01-27 03:43:44 +00:00
printf(" \e[96m%s\e[0m \e[0;3m%s\e[0m \e[30G\e[36m%s\e[0m\n", $command, $args, $info);
2017-01-27 03:36:23 +00:00
};
2017-01-27 03:30:50 +00:00
printf("\e[1mCommands:\e[0m\n");
2016-11-01 15:10:35 +00:00
foreach ($help as $command=>$info) {
2017-01-27 03:30:50 +00:00
if (strpos($command," ")!==false) {
list($command,$args) = explode(" ",$command,2);
} else $args=null;
2017-01-27 03:36:23 +00:00
$_($command, $args,$info);
}
if (count($ghelp)) {
2017-01-27 03:43:44 +00:00
printf("\e[1mCommands from parent contexts:\e[0m\n");
2017-01-27 03:30:50 +00:00
if (strpos($command," ")!==false) {
list($command,$args) = explode(" ",$command,2);
} else $args=null;
2017-01-27 03:36:23 +00:00
$_($command, $args,$info);
2016-11-01 15:10:35 +00:00
}
2017-01-27 03:43:44 +00:00
printf("\e[1mGlobal commands:\e[0m\n");
2017-01-27 03:36:23 +00:00
$_("exit", null, "Leave the shell");
$_(".", null, "Show the context tree");
$_("..", null, "Discard the current context and go to parent");
2016-11-01 14:12:11 +00:00
break;
case 'exit':
$this->stop();
break;
default:
return false;
}
return true;
}
/**
* Parse a string and execute the resulting command.
*
* @param string $command The string to parse
* @return mixed
*/
public function executeBuffer(string $command)
{
$args = str_getcsv($command, " ", "\"", "\\");
$command = array_shift($args);
try {
$this->executeCommand($command, ...$args);
} catch (Exception\ShellException $e) {
echo "\e[31;91;1m{$e->getMessage()}\e[0m\n";
}
}
2017-01-23 23:49:13 +00:00
/**
* Start the shell
*
*/
2016-04-25 18:47:30 +00:00
public function run()
2016-04-13 01:19:22 +00:00
{
2016-11-21 00:26:06 +00:00
try {
$this->lineReader = new LineRead();
2016-11-01 14:12:11 +00:00
2016-11-21 00:26:06 +00:00
$this->lineReader->setPromptText($this->prompt);
$this->lineReader->setPromptStyle($this->prompt_style?:new Style(Style::BR_GREEN));
$this->lineReader->setCommandStyle($this->input_style?:new Style(Style::GREEN));
2016-04-13 01:19:22 +00:00
2016-11-21 00:26:06 +00:00
$this->running = true;
2016-04-25 18:47:30 +00:00
$this->dispatchEvent(self::EVT_UPDATE_PROMPT);
$this->dispatchEvent(self::EVT_SHELL_START);
2016-11-01 14:12:11 +00:00
2016-11-21 00:26:06 +00:00
while ($this->running) {
// Update the input stuff, sleep if nothing to do.
if (!($buffer = $this->lineReader->update())) {
usleep(10000);
}
// Escape is handy too...
if ($buffer == "\e") {
$this->dispatchEvent(self::EVT_SHELL_ESCAPE);
2016-11-21 00:26:06 +00:00
continue;
}
// we get a ^C on ^C, so deal with the ^C.
if ($buffer == "\x03") {
$this->dispatchEvent(self::EVT_SHELL_ABORT);
2016-11-21 00:26:06 +00:00
$this->stop();
continue;
}
// Execute the buffer
ob_start();
$this->dispatchEvent("update");
foreach ($this->timers as $timer) {
$timer->update();
}
foreach ($this->tasks as $taskidx=>$task) {
$task->update();
if (!$task->isValid()) {
$this->dispatchEvent(self::EVT_TASK_DESTROYED, [
'task' => $task
]);
unset($this->tasks[$taskidx]);
}
}
2016-11-21 00:26:06 +00:00
if ($buffer) {
$this->executeBuffer($buffer);
}
$output = ob_get_contents();
ob_end_clean();
2016-11-01 14:12:11 +00:00
2016-11-21 00:26:06 +00:00
if (trim($output)) {
$this->lineReader->erase();
echo rtrim($output)."\n";
if ($this->running)
$this->lineReader->redraw();
2016-11-21 00:26:06 +00:00
}
2016-11-01 14:12:11 +00:00
2016-11-21 00:26:06 +00:00
if (!$this->context) {
$this->stop();
break;
2016-11-21 00:26:06 +00:00
}
2016-11-01 14:12:11 +00:00
2016-11-21 00:26:06 +00:00
if ($buffer) {
$this->dispatchEvent(self::EVT_UPDATE_PROMPT);
2016-11-21 00:26:06 +00:00
}
2016-11-01 14:15:47 +00:00
}
2016-11-21 00:26:06 +00:00
} catch (\Exception $e) {
fprintf(STDERR, "\e[31;1mFatal: Unhandled exception\e[0m\n\n%s\n", $e);
2016-11-01 14:12:11 +00:00
}
$this->dispatchEvent(self::EVT_SHELL_STOP);
2016-11-01 14:12:11 +00:00
$this->lineReader = null;
2016-04-13 01:19:22 +00:00
}
2017-01-23 23:49:13 +00:00
/**
* Helper function to emit an event with shell instance and context included.
*
* @param string $type The event type
* @param array[] $data The userdata of the event
*/
private function dispatchEvent($type, array $data=[])
{
$data['shell'] = $this;
$data['context'] = $this->context;
$event = new Event($type, $data);
$this->emitEvent($type, $event);
return $event;
}
public function getInput($prompt, callable $callback)
{
$this->addListener(Shell::EVT_UPDATE_PROMPT, [ $this, "onInputPrompt" ], $prompt);
$this->addListener(Shell::EVT_BEFORE_COMMAND, [ $this, "onInputHandler" ], $this->prompt, $callback);
}
public function onInputPrompt(Event $e, $prompt)
{
$this->setPrompt($prompt);
$e->stopPropagation();
$this->removeListener(Shell::EVT_UPDATE_PROMPT, [ $this, "onInputPrompt" ], $prompt);
}
public function onInputHandler(Event $e, $last_prompt, $callback)
{
// Restore the prompt
$this->setPrompt($last_prompt);
// Remove the listeners and compose the result string
$this->removeListener(Shell::EVT_BEFORE_COMMAND, [ $this, "onInputHandler" ], $last_prompt, $callback);
$input = trim($e->command." ".join(" ",$e->args));
$e->stopPropagation();
// Call the callback
call_user_func($callback, $input);
}
2017-01-23 23:49:13 +00:00
/**
* Stop the shell; calling this method will cause the main run() to return.
*
*/
2016-04-13 01:19:22 +00:00
public function stop()
{
$this->running = false;
}
}