Skip to content

Commit

Permalink
update some command logic
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Apr 12, 2022
1 parent 5d40745 commit c7b5b42
Show file tree
Hide file tree
Showing 7 changed files with 310 additions and 28 deletions.
34 changes: 24 additions & 10 deletions app/Component/ScriptRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Inhere\Kite\Component;

use Inhere\Console\Util\Show;
use Inhere\Kite\Concern\SimpleEventAwareTrait;
use Inhere\Kite\Helper\KiteUtil;
use Inhere\Kite\Helper\SysCmd;
use Inhere\Kite\Kite;
Expand Down Expand Up @@ -40,17 +41,16 @@
*/
class ScriptRunner extends AbstractObj
{
use SimpleEventAwareTrait;

public const TYPE_CMD = 'cmd';
public const TYPE_FILE = 'file';

private const LOAD_KITE_CODE = <<<'TXT'
function load_kite() {
if ($kiteDir = (string)getenv('KITE_PATH')) {
require $kiteDir. '/app/boot.php';
}
}

TXT;
/**
* handler: function(string $binName, array $args) {}
*/
public const EVT_ON_RUN_BEFORE = 'script.run.before';
public const EVT_ON_RUN_AFTER = 'script.run.after';

/**
* @var bool
Expand Down Expand Up @@ -116,6 +116,18 @@ function load_kite() {
'.go' => 'go run',
];

/**
* Class constructor.
*
* @param array $config
*/
public function __construct(array $config = [])
{
parent::__construct($config);

$this->setSupportEvents([self::EVT_ON_RUN_BEFORE, self::EVT_ON_RUN_AFTER]);
}

/**
* @param string $name
* @param array $runArgs
Expand Down Expand Up @@ -228,9 +240,11 @@ public function runScriptFile(string $scriptFile, array $runArgs): void
$command .= ' ' . implode(' ', $runArgs);
}

$this->fire(self::EVT_ON_RUN_BEFORE, $binName, $runArgs);
// not in phar.
if ($binName === 'php' && !KiteUtil::isInPhar()) {
OS::setEnvVar('KITE_PATH', Kite::basePath());
OS::setEnvVar('KITE_BOOT_FILE', Kite::getPath('app/boot.php'));
}

$this->executeScript($command, false, $workdir);
Expand Down Expand Up @@ -379,8 +393,8 @@ public function loadAllScriptFiles(): void
{
// $extMatch = '';
// foreach ($this->scriptDirs as $scriptDir) {
// $iter = Dir::getIterator($scriptDir);
// $files = Dir::getFiles($scriptDir, $extMatch);
// $iter = Dir::getIterator($scriptDir);
// $files = Dir::getFiles($scriptDir, $extMatch);
// }
}

Expand Down
207 changes: 207 additions & 0 deletions app/Concern/SimpleEventAwareTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
<?php declare(strict_types=1);

namespace Inhere\Kite\Concern;

use InvalidArgumentException;
use function count;
use function in_array;
use function preg_match;

/**
* Class SimpleEventStaticTrait
*
* @package Inhere\Console\Concern
*/
trait SimpleEventAwareTrait
{
/**
* set the supported events, if you need.
* if it is empty, will allow register any event.
*
* @var array<string>
*/
protected array $supportedEvents = [];

/**
* registered Events
*
* ```php
* [
* 'event' => bool, // is once event
* ]
* ```
*
* @var array
*/
private array $events = [];

/**
* events and handlers
*
* ```php
* [
* 'event' => callable, // event handler
* ]
* ```
*
* @var array<string, callable>
*/
private array $eventHandlers = [];

/**
* register a event handler
*
* @param string $event
* @param callable $handler
* @param bool $once
*/
public function on(string $event, callable $handler, bool $once = false): void
{
if (!$this->isSupportedEvent($event)) {
throw new InvalidArgumentException('register unsupported event: ' . $event);
}

$this->eventHandlers[$event][] = $handler;

if (!isset($this->events[$event])) {
$this->events[$event] = $once;
}
}

/**
* register a once event handler
*
* @param string $event
* @param callable $handler
*/
public function once(string $event, callable $handler): void
{
$this->on($event, $handler, true);
}

/**
* trigger event
*
* @param string $event
* @param mixed ...$args
*
* @return bool
*/
public function fire(string $event, ...$args): bool
{
if (!isset($this->events[$event])) {
return false;
}

// call event handlers of the event.
/** @var mixed $return */
$return = true;
foreach ((array)$this->eventHandlers[$event] as $cb) {
$return = $cb(...$args);
// return FALSE to stop go on handle.
if (false === $return) {
break;
}
}

// is a once event, remove it
if ($this->events[$event]) {
return $this->off($event);
}

return (bool)$return;
}

/**
* remove event and it's handlers
*
* @param string $event
*
* @return bool
*/
public function off(string $event): bool
{
if ($this->hasEvent($event)) {
unset($this->events[$event], $this->eventHandlers[$event]);
return true;
}

return false;
}

/**
* @param string $event
*
* @return bool
*/
public function hasEvent(string $event): bool
{
return isset($this->events[$event]);
}

/**
* @param string $event
*
* @return bool
*/
public function isOnce(string $event): bool
{
if ($this->hasEvent($event)) {
return $this->events[$event];
}

return false;
}

/**
* check $name is a supported event name
*
* @param string $event
*
* @return bool
*/
public function isSupportedEvent(string $event): bool
{
if (!$event || !preg_match('/[a-zA-Z][\w-]+/', $event)) {
return false;
}

if ($ets = $this->supportedEvents) {
return in_array($event, $ets, true);
}

return true;
}

/**
* @return array
*/
public function getSupportEvents(): array
{
return $this->supportedEvents;
}

/**
* @param array $supportedEvents
*/
public function setSupportEvents(array $supportedEvents): void
{
$this->supportedEvents = $supportedEvents;
}

/**
* @return array
*/
public function getEvents(): array
{
return $this->events;
}

/**
* @return int
*/
public function countEvents(): int
{
return count($this->events);
}
}
2 changes: 2 additions & 0 deletions app/Console/Command/ExprCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@

/**
* Class ExprCommand
*
* @
*/
class ExprCommand extends Command
{
Expand Down
73 changes: 59 additions & 14 deletions app/Console/Command/FindCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@
use Inhere\Console\Command;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
use Inhere\Kite\Common\Cmd;
use SplFileInfo;
use Toolkit\FsUtil\FileFinder;
use Toolkit\Stdlib\Helper\DataHelper;
use Toolkit\PFlag\FlagsParser;
use Toolkit\Stdlib\Helper\Assert;
use Toolkit\Stdlib\Std;
use function println;
use function strtr;

/**
* Class FindCommand
Expand All @@ -27,12 +32,31 @@ class FindCommand extends Command

public static function aliases(): array
{
return ['grep'];
return ['glob'];
}

protected function beforeInitFlagsParser(FlagsParser $fs): void
{
parent::beforeInitFlagsParser($fs);

$fs->setStopOnFistArg(false);
}

/**
* @options
* --paths, --path Include paths pattern. multi split by comma ','.
* --not-paths, --np Exclude paths pattern. multi split by comma ','. eg: node_modules,bin
* --names, --name Include file,dir name match pattern, multi split by comma ','.
* --not-names, --nn Exclude names pattern. multi split by comma ','.
* --only-dirs, --only-dir Only find dirs.
* --only-files, --only-file Only find files.
* --dirs, --dir, -d Find in the dirs
* --exec, -e Exec command for each find file/dir path.
* --dry-run, --try bool;Not real run the input command by --exec
*
* @arguments
* paths array;Find in the paths;true
* match Include paths pattern, same of the option --paths.
* dirs Find in the dirs, same of the option --paths.
*
* @param Input $input
* @param Output $output
Expand All @@ -41,23 +65,44 @@ public static function aliases(): array
*/
protected function execute(Input $input, Output $output): int
{
$paths = $this->flags->getArg('paths');
$output->info('find in the paths:' . DataHelper::toString($paths));
$fs = $this->flags;

$dirs = $this->flags->getOpt('dirs', $fs->getArg('dirs'));
Assert::notEmpty($dirs, 'dirs cannot be empty.');

$ff = FileFinder::create()->in($paths)
$output->info('Find in the dirs:' . Std::toString($dirs));

$ff = FileFinder::create()->in($dirs)
->skipUnreadableDirs()
->notFollowLinks()
->name('plugins')
->notPaths(['System', 'node_modules', 'bin/'])
// ->notNames(['System', 'node_modules', 'bin/'])
->onlyDirs();
->addNames($fs->getOpt('names'))
->notNames($fs->getOpt('not-names'))
->addPaths($fs->getOpt('paths', $fs->getArg('match')))
->notPaths($fs->getOpt('not-paths'));

if ($fs->getOpt('only-dirs')) {
$ff->onlyDirs();
} elseif ($fs->getOpt('only-files')) {
$ff->onlyFiles();
}

$cmdStr = $fs->getOpt('exec');
$output->aList($ff->getInfo());
$ff->each(function (SplFileInfo $info) {
echo $info->getPathname(), "\n";
});

$output->info('Completed!');
$cmd = Cmd::new()->setDryRun($fs->getOpt('dry-run'));
$output->colored('RESULT:', 'ylw');
$ff->each(function (SplFileInfo $info) use($cmd, $cmdStr) {
$fullPath = $info->getPathname();
println('F', $fullPath);

if ($cmdStr) {
$cmdStr = strtr($cmdStr, [
'{file}' => $fullPath,
]);

$cmd->setCmdline($cmdStr)->runAndPrint();
}
});
return 0;
}
}
Loading

0 comments on commit c7b5b42

Please sign in to comment.