Compare commits
25 Commits
Author | SHA1 | Date | |
---|---|---|---|
cee82fc740 | |||
c7b1a637c2 | |||
809c04abfa | |||
4cd5cc2620 | |||
5a45ca9c46 | |||
b6727bed80 | |||
0e5a25567c | |||
bdec60717f | |||
43a6475192 | |||
7bfd8453e7 | |||
482d8a54e5 | |||
b2a23f992d | |||
455574b6a5 | |||
46806e3d62 | |||
427cac578a | |||
ea09a15963 | |||
fe27eeb4a3 | |||
a2c1148c52 | |||
81dea747b2 | |||
ae17abb6c1 | |||
01ee043bac | |||
bb74b56fc4 | |||
3cbf504aed | |||
612e8d06c0 | |||
de7f12b7d5 |
25
CHANGELOG.md
Normal file
25
CHANGELOG.md
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
Changelog and Upgrade Instructions
|
||||||
|
==================================
|
||||||
|
|
||||||
|
## 0.2.x to 0.3.x
|
||||||
|
|
||||||
|
Major changes:
|
||||||
|
|
||||||
|
* The `Shell::EV_*` constants have been renamed to `Shell::EVT_*`.
|
||||||
|
* The `configure` method has been removed. If you really need to
|
||||||
|
extend the `Shell` class, use the constructor to configure your
|
||||||
|
shell (see *examples/timers.php*)
|
||||||
|
* Events are now dispatched using the *NoccyLabs/TinyEvent* library.
|
||||||
|
The main difference here is in how the event object received. The
|
||||||
|
shell instance is now passed in the object, and you can provide any
|
||||||
|
userdata to be passed on to the handler when you add the listener.
|
||||||
|
* The event `Shell::EVT_BAD_COMMAND` will be fired if a command can
|
||||||
|
not be found, assuming `Context->execute()` does not accept the
|
||||||
|
command. (see *examples/commandevents.php*)
|
||||||
|
|
||||||
|
New features:
|
||||||
|
|
||||||
|
* Tasks can now be added and removed from the shell. Tasks will receive
|
||||||
|
a call to their `update()` method once per main loop, until they are
|
||||||
|
removed or return false from the `isValid()` method. Tasks need to
|
||||||
|
implement the `TaskInterface` interface. (see *examples/tasks.php*)
|
12
README.md
12
README.md
@ -0,0 +1,12 @@
|
|||||||
|
NoccyLabs Shell Core
|
||||||
|
====================
|
||||||
|
|
||||||
|
This library helps make elegant command line applications that spawn an isolated shell.
|
||||||
|
It uses a standalone implementation for buffered input with support for arrow keys to
|
||||||
|
navigate the history and more.
|
||||||
|
|
||||||
|
Note that this library requirements a fully ANSI compatible terminal with UTF-8 support
|
||||||
|
in order to use colors, control the cursor position etc. As it uses `stty` to configure
|
||||||
|
input buffering, it will likely not work on Windows.
|
||||||
|
|
||||||
|
|
||||||
|
@ -13,5 +13,8 @@
|
|||||||
"psr-4": {
|
"psr-4": {
|
||||||
"NoccyLabs\\Shell\\": "lib/"
|
"NoccyLabs\\Shell\\": "lib/"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"noccylabs/tinyevent": "~0.1.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
36
examples/basic.php
Normal file
36
examples/basic.php
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
/*
|
||||||
|
* Basic shell example, demonstrates adding a listener to update the prompt with
|
||||||
|
* the current time as well as creating an "anonymous" context and adding a
|
||||||
|
* command to it. It also shows how to change the style of the prompt.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Style;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
|
$myShell = new Shell();
|
||||||
|
|
||||||
|
// Set the style of prompt and input
|
||||||
|
$myShell->setPromptStyle(new Style(Style::BR_GREEN, Style::GREEN));
|
||||||
|
$myShell->setInputStyle(new Style(Style::BR_CYAN));
|
||||||
|
|
||||||
|
// Add a listener to update the prompt
|
||||||
|
$myShell->addListener(Shell::EVT_UPDATE_PROMPT, function ($e) {
|
||||||
|
$e->shell->setPrompt(date("H:i:s").">");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set the initial prompt, not really needed.
|
||||||
|
$myShell->setPrompt("test>");
|
||||||
|
|
||||||
|
// Create an anonymous context and add a command
|
||||||
|
$ctx = $myShell->createContext("root");
|
||||||
|
$ctx->addCommand("hello", function () {
|
||||||
|
echo "Hello World!\n";
|
||||||
|
}, [ 'help'=>'Say hello' ]);
|
||||||
|
|
||||||
|
// Run the shell
|
||||||
|
$myShell->run();
|
20
examples/catchall.php
Normal file
20
examples/catchall.php
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
|
class CatchAllContext extends Context
|
||||||
|
{
|
||||||
|
public function execute($cmd, ...$arg)
|
||||||
|
{
|
||||||
|
printf("Executing: %s %s\n", $cmd, join(" ",$arg));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$myShell = new Shell();
|
||||||
|
$myShell->setPrompt("test>");
|
||||||
|
$myShell->pushContext(new CatchAllContext());
|
||||||
|
$myShell->run();
|
44
examples/commandevents.php
Normal file
44
examples/commandevents.php
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
/*
|
||||||
|
* This example demonstrates how to use events to catch commands that
|
||||||
|
* have not been handled by any context or builtin.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Style;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
|
$myShell = new Shell();
|
||||||
|
|
||||||
|
// Add a listeners for various command aspects
|
||||||
|
$myShell->addListener(Shell::EVT_BAD_COMMAND, function ($e) {
|
||||||
|
echo "EVT_BAD_COMMAND:\n";
|
||||||
|
printf("| command: %s\n", $e->command);
|
||||||
|
printf("|_args: %s\n", join(" ",$e->args));
|
||||||
|
});
|
||||||
|
$myShell->addListener(Shell::EVT_BEFORE_COMMAND, function ($e) {
|
||||||
|
echo "EVT_BEFORE_COMMAND:\n";
|
||||||
|
printf("| command: %s\n", $e->command);
|
||||||
|
printf("|_args: %s\n", join(" ",$e->args));
|
||||||
|
});
|
||||||
|
$myShell->addListener(Shell::EVT_AFTER_COMMAND, function ($e) {
|
||||||
|
echo "EVT_AFTER_COMMAND:\n";
|
||||||
|
printf("| command: %s\n", $e->command);
|
||||||
|
printf("| args: %s\n", join(" ",$e->args));
|
||||||
|
printf("|_type: %s\n", $e->type);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set the initial prompt, not really needed.
|
||||||
|
$myShell->setPrompt("test>");
|
||||||
|
|
||||||
|
// Create an anonymous context and add a command
|
||||||
|
$ctx = $myShell->createContext("root");
|
||||||
|
$ctx->addCommand("hello", function () {
|
||||||
|
echo "Hello World!\n";
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run the shell
|
||||||
|
$myShell->run();
|
27
examples/contexts.php
Normal file
27
examples/contexts.php
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
|
$shell = new Shell();
|
||||||
|
$shell->addListener("prompt", function ($event, $shell) {
|
||||||
|
$name = $shell->getContextPath();
|
||||||
|
$shell->setPrompt("shell{$name}> ");
|
||||||
|
});
|
||||||
|
|
||||||
|
$root = new Context();
|
||||||
|
$root->addCommand("test", function () {
|
||||||
|
echo "It works!\n";
|
||||||
|
});
|
||||||
|
$root->addCommand("context", function ($name) {
|
||||||
|
$context = new Context($name);
|
||||||
|
$context->name = $name;
|
||||||
|
return $context;
|
||||||
|
});
|
||||||
|
$shell->pushContext($root);
|
||||||
|
|
||||||
|
|
||||||
|
$shell->run();
|
||||||
|
|
19
examples/errors.php
Normal file
19
examples/errors.php
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
|
class CatchAllContext extends Context
|
||||||
|
{
|
||||||
|
public function execute($cmd, ...$arg)
|
||||||
|
{
|
||||||
|
throw new \Exception("Uh-oh! Error!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$myShell = new Shell();
|
||||||
|
$myShell->setPrompt("test>");
|
||||||
|
$myShell->pushContext(new CatchAllContext());
|
||||||
|
$myShell->run();
|
31
examples/input.php
Normal file
31
examples/input.php
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
/*
|
||||||
|
* This example demonstrates how to use events to catch commands that
|
||||||
|
* have not been handled by any context or builtin.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Style;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
|
$myShell = new Shell();
|
||||||
|
|
||||||
|
// Set the initial prompt, not really needed.
|
||||||
|
$myShell->setPrompt("test>");
|
||||||
|
|
||||||
|
// Create an anonymous context and add a command
|
||||||
|
$ctx = $myShell->createContext("root");
|
||||||
|
$ctx->addCommand("hello", function () use ($myShell) {
|
||||||
|
$myShell->getInput("What is your name?", function ($name) use ($myShell) {
|
||||||
|
echo "Hello, {$name}\n";
|
||||||
|
$myShell->getInput("Who is your daddy and what does he do?", function ($daddy) {
|
||||||
|
echo "{$daddy}? Oookay...\n";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run the shell
|
||||||
|
$myShell->run();
|
@ -4,16 +4,49 @@ require_once __DIR__."/../vendor/autoload.php";
|
|||||||
|
|
||||||
use NoccyLabs\Shell\Shell;
|
use NoccyLabs\Shell\Shell;
|
||||||
use NoccyLabs\Shell\Command;
|
use NoccyLabs\Shell\Command;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
class MyCommand extends Command
|
class MyCommand extends Command
|
||||||
{
|
{
|
||||||
public function getName()
|
|
||||||
{
|
|
||||||
return "mycommand";
|
|
||||||
}
|
|
||||||
public function execute()
|
public function execute()
|
||||||
{
|
{
|
||||||
$this->writeln("Executing command");
|
echo "Executing command";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyContext extends Context
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @command testme
|
||||||
|
* @args
|
||||||
|
* @help Useful test!
|
||||||
|
* @global
|
||||||
|
*/
|
||||||
|
public function test()
|
||||||
|
{
|
||||||
|
echo "Test\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @command context
|
||||||
|
* @help Create a new context
|
||||||
|
*/
|
||||||
|
public function context()
|
||||||
|
{
|
||||||
|
return new OtherContext("newcontext");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class OtherContext extends Context
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @command other
|
||||||
|
* @args
|
||||||
|
* @help Other test
|
||||||
|
*/
|
||||||
|
public function test()
|
||||||
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,30 +55,29 @@ class MyShell extends Shell
|
|||||||
|
|
||||||
protected $seq = 0;
|
protected $seq = 0;
|
||||||
|
|
||||||
protected function configure(array $config)
|
protected function configure()
|
||||||
{
|
{
|
||||||
$this->addCommand("hello", function () {
|
$context = new MyContext();
|
||||||
echo "world\n\rthis\n\ris\n\ra\ntest\n\r";
|
$this->pushContext($context);
|
||||||
|
$context->addCommand("hello", function () {
|
||||||
|
echo "world\nthis\nis\na\ntest\n";
|
||||||
});
|
});
|
||||||
$this->addCommand(new MyCommand());
|
$context->addCommand("mycommand", new MyCommand());
|
||||||
$this->updatePrompt();
|
$this->updatePrompt();
|
||||||
|
|
||||||
|
$this->addListener("update", function() {
|
||||||
|
static $lt;
|
||||||
|
$t = floor(microtime(true));
|
||||||
|
if ($t > $lt) {
|
||||||
|
$lt = $t + 5;
|
||||||
|
echo date("Y-m-d h:i:s")."\n";
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function updatePrompt()
|
protected function updatePrompt()
|
||||||
{
|
{
|
||||||
$this->setPrompt("test[{$this->seq}]: ");
|
$this->setPrompt("test[{$this->seq}]: ");
|
||||||
$fg = ($this->seq % 7) + 1;
|
|
||||||
$this->setPromptStyle("3{$fg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function onUpdate()
|
|
||||||
{
|
|
||||||
static $lt;
|
|
||||||
$t = floor(microtime(true));
|
|
||||||
if ($t > $lt) {
|
|
||||||
$lt = $t + 5;
|
|
||||||
echo date("Y-m-d h:i:s")."\n";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function onCommand($buffer)
|
protected function onCommand($buffer)
|
||||||
|
60
examples/tasks.php
Normal file
60
examples/tasks.php
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
/*
|
||||||
|
* This example demonstrates how to use events to catch commands that
|
||||||
|
* have not been handled by any context or builtin.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Style;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
use NoccyLabs\Shell\TaskInterface;
|
||||||
|
|
||||||
|
class MyTask implements TaskInterface
|
||||||
|
{
|
||||||
|
protected $start;
|
||||||
|
protected $last;
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->start = time();
|
||||||
|
}
|
||||||
|
public function update()
|
||||||
|
{
|
||||||
|
if ($this->last < time()) {
|
||||||
|
echo date("H:i:s")."\n";
|
||||||
|
$this->last = time();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public function isValid()
|
||||||
|
{
|
||||||
|
return (time() - $this->start < 5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$myShell = new Shell();
|
||||||
|
|
||||||
|
$myShell->addListener(Shell::EVT_TASK_CREATED, function ($e) {
|
||||||
|
echo "EVT_TASK_CREATED:\n";
|
||||||
|
printf("|_task: %s\n", get_class($e->task));
|
||||||
|
});
|
||||||
|
$myShell->addListener(Shell::EVT_TASK_DESTROYED, function ($e) {
|
||||||
|
echo "EVT_TASK_DESTROYED:\n";
|
||||||
|
printf("|_task: %s\n", get_class($e->task));
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
$myShell->addTask(new MyTask());
|
||||||
|
|
||||||
|
// Set the initial prompt, not really needed.
|
||||||
|
$myShell->setPrompt("test>");
|
||||||
|
|
||||||
|
// Create an anonymous context and add a command
|
||||||
|
$ctx = $myShell->createContext("root");
|
||||||
|
$ctx->addCommand("hello", function () {
|
||||||
|
echo "Hello World!\n";
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run the shell
|
||||||
|
$myShell->run();
|
60
examples/timers.php
Normal file
60
examples/timers.php
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
require_once __DIR__."/../vendor/autoload.php";
|
||||||
|
|
||||||
|
use NoccyLabs\Shell\Shell;
|
||||||
|
use NoccyLabs\Shell\Command;
|
||||||
|
use NoccyLabs\Shell\Context;
|
||||||
|
|
||||||
|
class MyContext extends Context
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @command testme
|
||||||
|
* @args
|
||||||
|
* @help Useful test!
|
||||||
|
*/
|
||||||
|
public function test()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyShell extends Shell
|
||||||
|
{
|
||||||
|
|
||||||
|
protected $seq = 0;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$context = new MyContext();
|
||||||
|
$this->pushContext($context);
|
||||||
|
$this->updatePrompt();
|
||||||
|
|
||||||
|
$t1 = $this->addTimer(5000, function () {
|
||||||
|
echo "5 seconds\n";
|
||||||
|
});
|
||||||
|
$app = $this;
|
||||||
|
$t2 = $this->addTimer(15000, function () use ($t1, $app) {
|
||||||
|
echo "Removing timers...\n";
|
||||||
|
$app->removeTimer($t1);
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function updatePrompt()
|
||||||
|
{
|
||||||
|
$this->setPrompt("test[{$this->seq}]: ");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function onCommand($buffer)
|
||||||
|
{
|
||||||
|
$this->seq++;
|
||||||
|
$this->updatePrompt();
|
||||||
|
parent::onCommand($buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
$myShell = new MyShell();
|
||||||
|
$myShell->run();
|
||||||
|
echo "Exiting\n";
|
@ -1,14 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace NoccyLabs\Shell\AutoComplete;
|
|
||||||
|
|
||||||
class Hinter implement HinterInterface
|
|
||||||
{
|
|
||||||
public function getHints()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public function addHinter(HinterInterface $hinter)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,7 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace NoccyLabs\Shell\AutoComplete;
|
|
||||||
|
|
||||||
interface HinterInterface
|
|
||||||
{
|
|
||||||
}
|
|
@ -23,7 +23,8 @@ abstract class Command
|
|||||||
$this->shell->writeln($str);
|
$this->shell->writeln($str);
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract public function getName();
|
public function getName()
|
||||||
|
{}
|
||||||
|
|
||||||
public function getDescription()
|
public function getDescription()
|
||||||
{}
|
{}
|
||||||
@ -31,8 +32,8 @@ abstract class Command
|
|||||||
public function getHelp()
|
public function getHelp()
|
||||||
{}
|
{}
|
||||||
|
|
||||||
public function run(array $args)
|
public function __invoke(...$args)
|
||||||
{
|
{
|
||||||
call_user_func_array([$this,"execute"], $args);
|
call_user_func([$this,"execute"], ...$args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
199
lib/Context.php
Normal file
199
lib/Context.php
Normal file
@ -0,0 +1,199 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace NoccyLabs\Shell;
|
||||||
|
|
||||||
|
class Context
|
||||||
|
{
|
||||||
|
protected $name;
|
||||||
|
|
||||||
|
protected $commands = [];
|
||||||
|
|
||||||
|
protected $commandInfo = [];
|
||||||
|
|
||||||
|
protected $data = [];
|
||||||
|
|
||||||
|
protected $parent;
|
||||||
|
|
||||||
|
protected $shell;
|
||||||
|
|
||||||
|
public function __construct($name=null, array $data=[])
|
||||||
|
{
|
||||||
|
$this->name = $name;
|
||||||
|
$this->data = $data;
|
||||||
|
$this->configure();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getContextInfo()
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setShell(Shell $shell)
|
||||||
|
{
|
||||||
|
$this->shell = $shell;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getShell()
|
||||||
|
{
|
||||||
|
return $this->shell;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setParent(Context $parent=null)
|
||||||
|
{
|
||||||
|
$this->parent = $parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getParent()
|
||||||
|
{
|
||||||
|
return $this->parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getRoot()
|
||||||
|
{
|
||||||
|
if (!$this->parent) {
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
$node = $this;
|
||||||
|
while ($parent = $node->getParent()) {
|
||||||
|
$node = $parent;
|
||||||
|
}
|
||||||
|
return $parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function configure()
|
||||||
|
{
|
||||||
|
// Override this to do setup stuff
|
||||||
|
$this->findCommands();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function findCommands()
|
||||||
|
{
|
||||||
|
$refl = new \ReflectionClass(get_called_class());
|
||||||
|
foreach ($refl->getMethods() as $method) {
|
||||||
|
$docblock = $method->getDocComment();
|
||||||
|
$lines = array_map(function ($line) {
|
||||||
|
return trim($line, "*/ \t");
|
||||||
|
}, explode("\n", $docblock));
|
||||||
|
$info = [];
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
if (preg_match("/^@(command|help|args|global)\\s*(.*)$/", $line, $match)) {
|
||||||
|
list($void,$key,$value) = $match;
|
||||||
|
$info[$key] = $value;
|
||||||
|
}
|
||||||
|
if (count($info)>0) {
|
||||||
|
$cmdName = array_key_exists("command",$info)?$info["command"]:$method->getName();
|
||||||
|
$this->addCommand($cmdName, [$this, $method->getName()], $info);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function addCommand($command, callable $handler, array $info=[])
|
||||||
|
{
|
||||||
|
$this->commands[$command] = $handler;
|
||||||
|
$this->commandInfo[$command] = $info;
|
||||||
|
ksort($this->commands);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setCommandHelp($command, $help)
|
||||||
|
{
|
||||||
|
if (!array_key_exists($command, $this->commandInfo)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->commandInfo[$command]['help'] = $help;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function addCommands(array $commands)
|
||||||
|
{
|
||||||
|
foreach ($commands as $command=>$handler) {
|
||||||
|
// Make it easier to connect commands direct to local functions
|
||||||
|
if (is_string($handler) && is_callable([$this,$handler])) {
|
||||||
|
$handler = [ $this,$handler ];
|
||||||
|
}
|
||||||
|
// Add the command to the command list
|
||||||
|
$this->addCommand($command, $handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasCommand($command)
|
||||||
|
{
|
||||||
|
return array_key_exists($command, $this->commands);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getCommand($command)
|
||||||
|
{
|
||||||
|
return $this->commands[$command];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getCommandHelp()
|
||||||
|
{
|
||||||
|
$ret = [];
|
||||||
|
foreach ($this->commands as $command=>$handler) {
|
||||||
|
$info = $this->commandInfo[$command];
|
||||||
|
$args = array_key_exists("args",$info)?$info['args']:"";
|
||||||
|
$help = array_key_exists("help",$info)?$info['help']:"";
|
||||||
|
$ret[trim("{$command} {$args}")] = $help;
|
||||||
|
}
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isCommandGlobal($command)
|
||||||
|
{
|
||||||
|
if (strpos($command," ")!==false) {
|
||||||
|
list($command, $void) = explode(" ",$command,2);
|
||||||
|
}
|
||||||
|
$info = $this->commandInfo[$command];
|
||||||
|
return array_key_exists('global', $info);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Catch-all handler for commands not defined in context, globally or builtin.
|
||||||
|
* Override this function and return true if the command is handled ok.
|
||||||
|
*
|
||||||
|
* @param string $command The command to execute
|
||||||
|
* @param string[] $args The arguments to the command
|
||||||
|
* @return bool True if the command was handled
|
||||||
|
*/
|
||||||
|
public function execute($command, ...$args)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the name of the context
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public function getName()
|
||||||
|
{
|
||||||
|
return $this->name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __get($key)
|
||||||
|
{
|
||||||
|
if (!array_key_exists($key,$this->data)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return $this->data[$key];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __set($key,$value)
|
||||||
|
{
|
||||||
|
$this->data[$key] = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __isset($key)
|
||||||
|
{
|
||||||
|
return array_key_exists($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __unset($key)
|
||||||
|
{
|
||||||
|
unset($this->data[$key]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getData()
|
||||||
|
{
|
||||||
|
return $this->data;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
6
lib/Exception/BadCommandException.php
Normal file
6
lib/Exception/BadCommandException.php
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace NoccyLabs\Shell\Exception;
|
||||||
|
|
||||||
|
class BadCommandException extends ShellException
|
||||||
|
{}
|
8
lib/Exception/ShellException.php
Normal file
8
lib/Exception/ShellException.php
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace NoccyLabs\Shell\Exception;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
|
||||||
|
class ShellException extends Exception
|
||||||
|
{}
|
@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
namespace NoccyLabs\Shell;
|
namespace NoccyLabs\Shell;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a readline-like implementation in pure PHP.
|
||||||
|
*
|
||||||
|
*/
|
||||||
class LineRead
|
class LineRead
|
||||||
{
|
{
|
||||||
|
|
||||||
@ -15,6 +19,8 @@ class LineRead
|
|||||||
protected $buffer = null;
|
protected $buffer = null;
|
||||||
|
|
||||||
protected $history = [];
|
protected $history = [];
|
||||||
|
|
||||||
|
protected $stashedBuffer = null;
|
||||||
|
|
||||||
protected $posHistory = 0;
|
protected $posHistory = 0;
|
||||||
|
|
||||||
@ -34,7 +40,7 @@ class LineRead
|
|||||||
{
|
{
|
||||||
stream_set_blocking(STDIN, false);
|
stream_set_blocking(STDIN, false);
|
||||||
$this->sttyOld = trim(exec('stty -g'));
|
$this->sttyOld = trim(exec('stty -g'));
|
||||||
exec('stty raw -echo'); // isig');
|
exec('stty raw -echo opost onlret'); // isig');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function __destruct()
|
public function __destruct()
|
||||||
@ -61,13 +67,16 @@ class LineRead
|
|||||||
{
|
{
|
||||||
$prompt = $this->prompt;
|
$prompt = $this->prompt;
|
||||||
$buffer = $this->buffer;
|
$buffer = $this->buffer;
|
||||||
$cursor = strlen($this->prompt) + 1 + $this->posCursor - $this->posScroll;
|
|
||||||
|
if ($this->posCursor > strlen($this->buffer)) {
|
||||||
|
$this->posCursor = strlen($this->buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
$cursor = strlen($this->prompt) + 2 + $this->posCursor - $this->posScroll;
|
||||||
|
|
||||||
$promptStyle = $this->styleToAnsi($this->promptStyle);
|
|
||||||
$commandStyle = $this->styleToAnsi($this->commandStyle);
|
|
||||||
$endStyle = "\e[0m";
|
$endStyle = "\e[0m";
|
||||||
|
|
||||||
fprintf(STDOUT, "\r\e[2K{$promptStyle}%s{$commandStyle}%s\e[%dG{$endStyle}", $prompt, $buffer, $cursor);
|
fprintf(STDOUT, "\r\e[2K%s %s\e[%dG{$endStyle}", ($this->promptStyle)($prompt), ($this->commandStyle)($buffer), $cursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function styleToAnsi($style)
|
protected function styleToAnsi($style)
|
||||||
@ -87,6 +96,10 @@ class LineRead
|
|||||||
$returnBuffer = null;
|
$returnBuffer = null;
|
||||||
while (strlen($keyBuffer)>0) {
|
while (strlen($keyBuffer)>0) {
|
||||||
if ($keyBuffer[0] == "\e") {
|
if ($keyBuffer[0] == "\e") {
|
||||||
|
if (strlen($keyBuffer)==1) {
|
||||||
|
$keyBuffer = "";
|
||||||
|
return "\e";
|
||||||
|
}
|
||||||
if ($keyBuffer[1] == "[") {
|
if ($keyBuffer[1] == "[") {
|
||||||
$ctrlChar = substr($keyBuffer, 0,3);
|
$ctrlChar = substr($keyBuffer, 0,3);
|
||||||
$keyBuffer = substr($keyBuffer, 3);
|
$keyBuffer = substr($keyBuffer, 3);
|
||||||
@ -115,8 +128,10 @@ class LineRead
|
|||||||
}
|
}
|
||||||
} elseif ($keyCode == 13) {
|
} elseif ($keyCode == 13) {
|
||||||
$returnBuffer = $this->buffer;
|
$returnBuffer = $this->buffer;
|
||||||
|
array_unshift($this->history, $this->buffer);
|
||||||
$this->buffer = null;
|
$this->buffer = null;
|
||||||
$this->posCursor = 0;
|
$this->posCursor = 0;
|
||||||
|
$this->posHistory = 0;
|
||||||
printf("\n\r");
|
printf("\n\r");
|
||||||
$this->state = self::STATE_IDLE;
|
$this->state = self::STATE_IDLE;
|
||||||
}
|
}
|
||||||
@ -148,7 +163,36 @@ class LineRead
|
|||||||
$this->redraw();
|
$this->redraw();
|
||||||
break;
|
break;
|
||||||
case "\e[A": // up
|
case "\e[A": // up
|
||||||
|
if ($this->posHistory == 0) {
|
||||||
|
$this->stashedBuffer = $this->buffer;
|
||||||
|
}
|
||||||
|
if ($this->posCursor == strlen($this->buffer)) {
|
||||||
|
$this->posCursor = -1;
|
||||||
|
}
|
||||||
|
if ($this->posHistory < count($this->history)) {
|
||||||
|
$this->posHistory++;
|
||||||
|
$this->buffer = $this->history[$this->posHistory-1];
|
||||||
|
}
|
||||||
|
if ($this->posCursor == -1) {
|
||||||
|
$this->posCursor = strlen($this->buffer);
|
||||||
|
}
|
||||||
|
$this->redraw();
|
||||||
|
break;
|
||||||
case "\e[B": // down
|
case "\e[B": // down
|
||||||
|
if ($this->posCursor == strlen($this->buffer)) {
|
||||||
|
$this->posCursor = -1;
|
||||||
|
}
|
||||||
|
if ($this->posHistory > 1) {
|
||||||
|
$this->posHistory--;
|
||||||
|
$this->buffer = $this->history[$this->posHistory-1];
|
||||||
|
} elseif ($this->posHistory > 0) {
|
||||||
|
$this->posHistory--;
|
||||||
|
$this->buffer = $this->stashedBuffer;
|
||||||
|
}
|
||||||
|
if ($this->posCursor == -1) {
|
||||||
|
$this->posCursor = strlen($this->buffer);
|
||||||
|
}
|
||||||
|
$this->redraw();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
fprintf(STDERR, "\n%s\n", substr($code,1));
|
fprintf(STDERR, "\n%s\n", substr($code,1));
|
||||||
@ -160,12 +204,14 @@ class LineRead
|
|||||||
$this->commandStyle = $style;
|
$this->commandStyle = $style;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function setPrompt($prompt, $style=null)
|
public function setPromptText($prompt)
|
||||||
{
|
{
|
||||||
$this->prompt = $prompt;
|
$this->prompt = $prompt;
|
||||||
if ($style) {
|
}
|
||||||
$this->promptStyle = $style;
|
|
||||||
}
|
public function setPromptStyle($style)
|
||||||
|
{
|
||||||
|
$this->promptStyle = $style;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
619
lib/Shell.php
619
lib/Shell.php
@ -3,127 +3,576 @@
|
|||||||
namespace NoccyLabs\Shell;
|
namespace NoccyLabs\Shell;
|
||||||
|
|
||||||
use NoccyLabs\Shell\LineRead;
|
use NoccyLabs\Shell\LineRead;
|
||||||
|
use NoccyLabs\TinyEvent\EventEmitterTrait;
|
||||||
|
use NoccyLabs\TinyEvent\Event;
|
||||||
|
|
||||||
abstract class Shell
|
class Shell
|
||||||
{
|
{
|
||||||
protected $prompt;
|
use EventEmitterTrait;
|
||||||
|
|
||||||
protected $promptStyle;
|
const EVT_UPDATE_PROMPT = "shell.prompt"; // called to update the prompt
|
||||||
|
const EVT_BEFORE_COMMAND = "shell.command.before"; // before a command is executed
|
||||||
protected $commandStyle;
|
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
|
||||||
|
|
||||||
public function __construct(array $config=[])
|
/**
|
||||||
|
* @var LineRead The lineread instance
|
||||||
|
*/
|
||||||
|
protected $lineReader = null;
|
||||||
|
/**
|
||||||
|
* @var Context The current context
|
||||||
|
*/
|
||||||
|
protected $context = null;
|
||||||
|
/**
|
||||||
|
* @var Context[] The stack of parent contexts
|
||||||
|
*/
|
||||||
|
protected $contextStack = [];
|
||||||
|
/**
|
||||||
|
* @var object[] Created timers
|
||||||
|
*/
|
||||||
|
protected $timers = [];
|
||||||
|
/**
|
||||||
|
* @var TaskInterface[] Created tasks
|
||||||
|
*/
|
||||||
|
protected $tasks = [];
|
||||||
|
/**
|
||||||
|
* @var string The prompt string
|
||||||
|
*/
|
||||||
|
protected $prompt = ">";
|
||||||
|
/**
|
||||||
|
* @var Style The style applied to the prompt
|
||||||
|
*/
|
||||||
|
protected $prompt_style = null;
|
||||||
|
/**
|
||||||
|
* @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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->configure($config);
|
$t = $this;
|
||||||
|
register_shutdown_function(function () use (&$t) {
|
||||||
|
if ($t) unset($t);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract protected function configure(array $config);
|
/**
|
||||||
|
* Destructor
|
||||||
public function addCommand($command, callable $handler=null)
|
*
|
||||||
|
*/
|
||||||
|
public function __destruct()
|
||||||
{
|
{
|
||||||
if (!$handler) {
|
if ($this->lineReader) {
|
||||||
if (!($command instanceof Command)) {
|
$this->lineReader = null;
|
||||||
throw new \RuntimeException("Handler is not callable nor a Command");
|
}
|
||||||
}
|
}
|
||||||
$command->setShell($this);
|
|
||||||
$this->commands[$command->getName()] = $command;
|
/**
|
||||||
|
* Push a new primary context, saving the previous contexts on a stack.
|
||||||
|
*
|
||||||
|
* @param Context $context
|
||||||
|
*/
|
||||||
|
public function pushContext(Context $context)
|
||||||
|
{
|
||||||
|
if ($this->context) {
|
||||||
|
$context->setParent($this->context);
|
||||||
|
array_unshift($this->contextStack, $this->context);
|
||||||
|
}
|
||||||
|
$context->setShell($this);
|
||||||
|
$this->context = $context;
|
||||||
|
$this->dispatchEvent(self::EVT_CONTEXT_CHANGED);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pop the current context.
|
||||||
|
*
|
||||||
|
* @return Context
|
||||||
|
*/
|
||||||
|
public function popContext()
|
||||||
|
{
|
||||||
|
$previous = $this->context;
|
||||||
|
if (count($this->contextStack)>0) {
|
||||||
|
$this->context = array_shift($this->contextStack);
|
||||||
} else {
|
} else {
|
||||||
$this->commands[$command] = $handler;
|
$this->context = null;
|
||||||
|
}
|
||||||
|
$this->dispatchEvent(self::EVT_CONTEXT_CHANGED);
|
||||||
|
return $previous;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getContextPath($separator=":")
|
||||||
|
{
|
||||||
|
// Return null if we don't have a current context
|
||||||
|
if (!$this->context)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
// Assemble the contexts to walk
|
||||||
|
$stack = [ $this->context->getName() ];
|
||||||
|
foreach ($this->contextStack as $context) {
|
||||||
|
$stack[] = $context->getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reverse the order to make it more logical
|
||||||
|
$stack = array_reverse($stack);
|
||||||
|
return join($separator,$stack);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new empty context and push it on the stack.
|
||||||
|
*
|
||||||
|
* @param string $name The name of the context to create
|
||||||
|
* @return Context The created context
|
||||||
|
*/
|
||||||
|
public function createContext($name)
|
||||||
|
{
|
||||||
|
$context = new Context($name);
|
||||||
|
$this->pushContext($context);
|
||||||
|
return $context;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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=[])
|
||||||
|
{
|
||||||
|
$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;
|
||||||
|
$this->next = microtime(true) + $this->interval;
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a created timer.
|
||||||
|
*
|
||||||
|
* @param Timer $timer
|
||||||
|
*/
|
||||||
|
public function removeTimer($timer)
|
||||||
|
{
|
||||||
|
$this->timers = array_filter($this->timers, function ($v) use ($timer) {
|
||||||
|
return ($v !== $timer);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the prompt text
|
||||||
|
*
|
||||||
|
* @param string $text The text
|
||||||
|
*/
|
||||||
|
public function setPrompt($text)
|
||||||
|
{
|
||||||
|
$this->prompt = $text;
|
||||||
|
|
||||||
|
if ($this->lineReader) {
|
||||||
|
$this->lineReader->setPromptText($text);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function execute($command)
|
/**
|
||||||
|
* Set the prompt style
|
||||||
|
*
|
||||||
|
* @param Style $style The style to apply to the prompt
|
||||||
|
*/
|
||||||
|
public function setPromptStyle(Style $style)
|
||||||
{
|
{
|
||||||
if (is_array($command)) {
|
$this->prompt_style = $style;
|
||||||
foreach ($command as $cmd) {
|
|
||||||
$this->execute($cmd);
|
if ($this->lineReader) {
|
||||||
|
$this->lineReader->setPromptStyle($style);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a command and return a closure.
|
||||||
|
*
|
||||||
|
* @return callable The command
|
||||||
|
*/
|
||||||
|
private function findCommand($command)
|
||||||
|
{
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// No handler...
|
||||||
|
if (empty($handler)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return closure
|
||||||
|
return function (...$args) use ($handler) {
|
||||||
|
return call_user_func($handler, ...$args);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a command with arguments.
|
||||||
|
*
|
||||||
|
* @param string $command The command name to execute
|
||||||
|
* @param string ...$args Arguments
|
||||||
|
* @return mixed
|
||||||
|
* @throws Exception\BadCommandExcception
|
||||||
|
*/
|
||||||
|
public function executeCommand($command, ...$args)
|
||||||
|
{
|
||||||
|
if ($this->dispatchEvent(self::EVT_BEFORE_COMMAND, [
|
||||||
|
'command' => $command,
|
||||||
|
'args' => $args
|
||||||
|
])->isPropagationStopped()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->executeBuiltin($command, ...$args)) {
|
||||||
|
$this->dispatchEvent(self::EVT_AFTER_COMMAND, [
|
||||||
|
'command' => $command,
|
||||||
|
'args' => $args,
|
||||||
|
'type' => 'builtin'
|
||||||
|
]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$buffer = str_getcsv($command, " ", "\"", "\\");
|
// Call the handler if the command was found
|
||||||
|
if (($target = $this->findCommand($command))) {
|
||||||
if (count($buffer)>0) {
|
$ret = $target(...$args);
|
||||||
$this->onCommand($buffer);
|
if ($ret instanceof Context) {
|
||||||
}
|
$this->pushContext($ret);
|
||||||
}
|
|
||||||
|
|
||||||
protected function onCommand($buffer)
|
|
||||||
{
|
|
||||||
$this->executeBuffer($buffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function executeBuffer(array $buffer)
|
|
||||||
{
|
|
||||||
$commandName = array_shift($buffer);
|
|
||||||
if (array_key_exists($commandName, $this->commands)) {
|
|
||||||
$command = $this->commands[$commandName];
|
|
||||||
if ($command instanceof Command) {
|
|
||||||
$command->run($buffer);
|
|
||||||
} else {
|
|
||||||
call_user_func_array($command,$buffer);
|
|
||||||
}
|
}
|
||||||
|
$this->dispatchEvent(self::EVT_AFTER_COMMAND, [
|
||||||
|
'command' => $command,
|
||||||
|
'args' => $args,
|
||||||
|
'type' => 'command'
|
||||||
|
]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$this->writeln("Bad command: ".$commandName);
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Throw error if the command could not be found
|
||||||
|
throw new Exception\BadCommandException("Command {$command} not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
public function writeln($output)
|
/**
|
||||||
{
|
* Execute a built-in command
|
||||||
echo "\r\e[K\e[0m".$output."\n";
|
*
|
||||||
}
|
* @param string $command Command name
|
||||||
|
* @param mixed ...$args Arguments
|
||||||
protected function onUpdate()
|
* @return bool True if the command was handled OK
|
||||||
|
*/
|
||||||
|
public function executeBuiltin($command, ...$args)
|
||||||
{
|
{
|
||||||
|
switch ($command) {
|
||||||
|
case '.':
|
||||||
|
$type = basename(strtr(get_class($this->context), "\\", "/"));
|
||||||
|
printf("%s<%s>: %s\n", $type, $this->context->getName(), $this->context->getContextInfo());
|
||||||
|
$level = 0;
|
||||||
|
foreach ($this->contextStack as $context) {
|
||||||
|
$type = basename(strtr(get_class($context), "\\", "/"));
|
||||||
|
printf(" %s└─%s<%s>: %s\n", str_repeat(" ",$level++), $type, $context->getName(), $context->getContextInfo());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case '..':
|
||||||
|
if (count($this->contextStack)>0)
|
||||||
|
$this->popContext();
|
||||||
|
break;
|
||||||
|
case 'help':
|
||||||
|
$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);
|
||||||
|
printf("Commands in current context:\n");
|
||||||
|
foreach ($help as $command=>$info) {
|
||||||
|
printf(" %-20s %s\n", $command, $info);
|
||||||
|
}
|
||||||
|
if (count($ghelp)) {
|
||||||
|
printf("\nImported from parent contexts:\n");
|
||||||
|
foreach ($ghelp as $command=>$info) {
|
||||||
|
printf(" %-20s %s\n", $command, $info);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("\nGlobal commands:\n");
|
||||||
|
printf(" %-20s %s\n", "exit", "Leave the shell");
|
||||||
|
printf(" %-20s %s\n", "..", "Discard the current context and go to parent");
|
||||||
|
break;
|
||||||
|
case 'exit':
|
||||||
|
$this->stop();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function setPrompt($prompt)
|
/**
|
||||||
|
* Parse a string and execute the resulting command.
|
||||||
|
*
|
||||||
|
* @param string $command The string to parse
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function executeBuffer(string $command)
|
||||||
{
|
{
|
||||||
$this->prompt = $prompt;
|
$args = str_getcsv($command, " ", "\"", "\\");
|
||||||
}
|
$command = array_shift($args);
|
||||||
|
|
||||||
public function setPromptStyle($style)
|
try {
|
||||||
{
|
$this->executeCommand($command, ...$args);
|
||||||
$this->promptStyle = $style;
|
} catch (Exception\ShellException $e) {
|
||||||
}
|
echo "\e[31;91;1m{$e->getMessage()}\e[0m\n";
|
||||||
|
}
|
||||||
public function setCommandStyle($style)
|
|
||||||
{
|
|
||||||
$this->commandStyle = $style;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start the shell
|
||||||
|
*
|
||||||
|
*/
|
||||||
public function run()
|
public function run()
|
||||||
{
|
{
|
||||||
$lineRead = new LineRead();
|
try {
|
||||||
|
$this->lineReader = new LineRead();
|
||||||
$lineRead->setCommandStyle($this->commandStyle);
|
|
||||||
|
|
||||||
$this->running = true;
|
$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));
|
||||||
|
|
||||||
do {
|
$this->running = true;
|
||||||
$lineRead->setPrompt($this->prompt, $this->promptStyle);
|
|
||||||
$buffer = $lineRead->update();
|
$this->dispatchEvent(self::EVT_UPDATE_PROMPT);
|
||||||
if ($buffer == "\x03") {
|
$this->dispatchEvent(self::EVT_SHELL_START);
|
||||||
$this->stop();
|
|
||||||
continue;
|
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);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// we get a ^C on ^C, so deal with the ^C.
|
||||||
|
if ($buffer == "\x03") {
|
||||||
|
$this->dispatchEvent(self::EVT_SHELL_ABORT);
|
||||||
|
$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]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($buffer) {
|
||||||
|
$this->executeBuffer($buffer);
|
||||||
|
}
|
||||||
|
$output = ob_get_contents();
|
||||||
|
ob_end_clean();
|
||||||
|
|
||||||
|
if (trim($output)) {
|
||||||
|
$this->lineReader->erase();
|
||||||
|
echo rtrim($output)."\n";
|
||||||
|
if ($this->running)
|
||||||
|
$this->lineReader->redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$this->context) {
|
||||||
|
$this->stop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($buffer) {
|
||||||
|
$this->dispatchEvent(self::EVT_UPDATE_PROMPT);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ob_start();
|
|
||||||
$this->onUpdate();
|
} catch (\Exception $e) {
|
||||||
if ($buffer !== null) {
|
fprintf(STDERR, "\e[31;1mFatal: Unhandled exception\e[0m\n\n%s\n", $e);
|
||||||
$this->execute($buffer);
|
}
|
||||||
}
|
|
||||||
$buf = ob_get_contents();
|
$this->dispatchEvent(self::EVT_SHELL_STOP);
|
||||||
ob_end_clean();
|
|
||||||
if ($buf) {
|
$this->lineReader = null;
|
||||||
$lineRead->erase();
|
|
||||||
echo str_replace("\n", "\r\n", rtrim($buf)."\n");
|
|
||||||
$lineRead->redraw();
|
|
||||||
}
|
|
||||||
usleep(10000);
|
|
||||||
} while ($this->running);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop the shell; calling this method will cause the main run() to return.
|
||||||
|
*
|
||||||
|
*/
|
||||||
public function stop()
|
public function stop()
|
||||||
{
|
{
|
||||||
$this->running = false;
|
$this->running = false;
|
||||||
|
57
lib/Style.php
Normal file
57
lib/Style.php
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace NoccyLabs\Shell;
|
||||||
|
|
||||||
|
class Style
|
||||||
|
{
|
||||||
|
const NONE = null;
|
||||||
|
|
||||||
|
const BLACK = 0;
|
||||||
|
const RED = 1;
|
||||||
|
const GREEN = 2;
|
||||||
|
const YELLOW = 3;
|
||||||
|
const BLUE = 4;
|
||||||
|
const MAGENTA = 5;
|
||||||
|
const CYAN = 6;
|
||||||
|
const WHITE = 7;
|
||||||
|
|
||||||
|
const GRAY = 8;
|
||||||
|
const BR_RED = 9;
|
||||||
|
const BR_GREEN = 10;
|
||||||
|
const BR_YELLOW = 11;
|
||||||
|
const BR_BLUE = 12;
|
||||||
|
const BR_MAGENTA = 13;
|
||||||
|
const BR_CYAN = 14;
|
||||||
|
const BR_WHITE = 15;
|
||||||
|
|
||||||
|
const A_INTENSE = 1;
|
||||||
|
const A_UNDERLINE = 4;
|
||||||
|
const A_INVERSE = 7;
|
||||||
|
|
||||||
|
protected $fg = self::NONE;
|
||||||
|
|
||||||
|
protected $bg = self::NONE;
|
||||||
|
|
||||||
|
public function __construct($fg=self::NONE, $bg=self::NONE)
|
||||||
|
{
|
||||||
|
$this->fg = $fg;
|
||||||
|
$this->bg = $bg;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __invoke($string)
|
||||||
|
{
|
||||||
|
$pre = null; $post = null;
|
||||||
|
if ($this->fg !== self::NONE) {
|
||||||
|
$pre.= "\e[".(($this->fg > 7)?(90+($this->fg-8)):(30+$this->fg))."m";
|
||||||
|
$post.= "\e[39m";
|
||||||
|
}
|
||||||
|
if ($this->bg !== self::NONE) {
|
||||||
|
$pre.= "\e[".(($this->bg > 7)?(100+($this->bg-8)):(40+$this->bg))."m";
|
||||||
|
$post.= "\e[49m";
|
||||||
|
}
|
||||||
|
|
||||||
|
return $pre . $string . $post;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
10
lib/TaskInterface.php
Normal file
10
lib/TaskInterface.php
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace NoccyLabs\Shell;
|
||||||
|
|
||||||
|
interface TaskInterface
|
||||||
|
{
|
||||||
|
public function update();
|
||||||
|
|
||||||
|
public function isValid();
|
||||||
|
}
|
Reference in New Issue
Block a user