Skip to content

Commit

Permalink
feat: add new simple command: which
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Dec 24, 2021
1 parent aec48b2 commit 4ca885a
Show file tree
Hide file tree
Showing 15 changed files with 262 additions and 130 deletions.
10 changes: 10 additions & 0 deletions app/Component/ScriptRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ class ScriptRunner extends AbstractObj
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;


/**
* @var bool
*/
Expand Down
67 changes: 67 additions & 0 deletions app/Console/Command/CatCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php declare(strict_types=1);
/**
* This file is part of Kite.
*
* @link https://github.com/inhere
* @author https://github.com/inhere
* @license MIT
*/

namespace Inhere\Kite\Console\Command;

use Inhere\Console\Command;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
use Inhere\Kite\Console\Component\ContentsAutoReader;
use PhpPkg\Config\ConfigBox;
use PhpPkg\Config\ConfigUtil;

/**
* Class CatCommand
*/
class CatCommand extends Command
{
protected static string $name = 'cat';

protected static string $desc = 'read and show contents';

protected function configure(): void
{
$this->flags
->addOpt('type', 't', 'content type. allow: raw, txt, json', 'string', false, 'raw')
->addArg('source', <<<'TXT'
The source contents.
Special input:
input '@c' or '@cb' or '@clipboard' - will read from Clipboard
input empty or '@i' or '@stdin' - will read from STDIN
input '@FILEPATH' - will read from the filepath
TXT
);
}

/**
* @param Input $input
* @param Output $output
*/
protected function execute(Input $input, Output $output)
{
$txt = ContentsAutoReader::readFrom($this->flags->getArg('source'), [
'throwOnEmpty' => false
]);
if (!$txt) {
return;
}

switch ($this->flags->getArg('type')) {
case 'yml':
case 'yaml':
ConfigUtil::readFromString(ConfigBox::FORMAT_YAML, $txt);
break;
case 'raw':
case 'txt':
case 'text':
default:
$output->writeln($txt);
}
}
}
4 changes: 2 additions & 2 deletions app/Console/Component/ContentsAutoReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class ContentsAutoReader extends AbstractObj

/**
* @param string $source
* @param array $opts
* @param array{print: bool, loadedFile: string, throwOnEmpty: bool} $opts
*
* @return string
*/
Expand All @@ -52,7 +52,7 @@ public static function readFrom(string $source, array $opts = []): string
* - input '@FILEPATH' or FILEPATH - will read from the filepath.
*
* @param string $source the input text
* @param array{print: bool, loadedFile: string, throwOnEmpty: true} $opts
* @param array{print: bool, loadedFile: string, throwOnEmpty: bool} $opts
*
* @return string
*/
Expand Down
36 changes: 32 additions & 4 deletions app/Console/Component/ContentsAutoWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,18 @@ class ContentsAutoWriter
/**
* @param string $output
* @param string $contents
* @param array{printTips: bool} $opts
*
* @return bool
*/
public static function writeTo(string $output, string $contents): bool
public static function writeTo(string $output, string $contents, array $opts = []): bool
{
return (new self)->setOutput($output)->write($contents);
return (new self)
->setOutput($output)
->withConfig(function (self $writer) use ($opts) {
$writer->setPrintTips($opts['printTips'] ?? true);
})
->write($contents);
}

/**
Expand All @@ -45,6 +51,17 @@ public function __construct(string $output = '')
$this->output = $output;
}

/**
* @param callable $fn
*
* @return $this
*/
public function withConfig(callable $fn): self
{
$fn($this);
return $this;
}

/**
* @param string $contents
*
Expand All @@ -66,7 +83,7 @@ public function write(string $contents): bool
Kite::cliApp()->getOutput()->colored('RESULT:');
}

Kite::cliApp()->getOutput()->writeRaw($contents);
Kite::cliApp()->getOutput()->write($contents);
} else {
// write to file
if ($this->printTips) {
Expand All @@ -85,7 +102,7 @@ public function write(string $contents): bool
/**
* @return bool
*/
public function IsToStdout(): bool
public function isToStdout(): bool
{
return !$this->output || in_array($this->output, ['@o', '@stdout'], true);
}
Expand All @@ -100,4 +117,15 @@ public function setOutput(string $output): self
$this->output = $output;
return $this;
}

/**
* @param bool $printTips
*
* @return ContentsAutoWriter
*/
public function setPrintTips(bool $printTips): self
{
$this->printTips = $printTips;
return $this;
}
}
127 changes: 31 additions & 96 deletions app/Console/Controller/ConvertController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,26 @@

namespace Inhere\Kite\Console\Controller;

use Inhere\Console\Component\Formatter\JSONPretty;
use Inhere\Console\Controller;
use Inhere\Console\Exception\PromptException;
use Inhere\Console\IO\Output;
use Inhere\Kite\Console\Component\Clipboard;
use Inhere\Kite\Console\Component\ContentsAutoReader;
use Inhere\Kite\Console\Component\ContentsAutoWriter;
use Inhere\Kite\Helper\KiteUtil;
use Inhere\Kite\Lib\Convert\JavaProperties;
use Inhere\Kite\Lib\Parser\DBTable;
use Inhere\Kite\Lib\Parser\Text\TextParser;
use Inhere\Kite\Lib\Stream\ListStream;
use InvalidArgumentException;
use PhpPkg\Config\ConfigUtil;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Yaml;
use Toolkit\FsUtil\File;
use Toolkit\PFlag\FlagsParser;
use Toolkit\Stdlib\Json;
use function array_pad;
use function array_shift;
use function base_convert;
use function date;
use function file_get_contents;
use function implode;
use function is_file;
use function strlen;
use function substr;
use function trim;

/**
* Class ConvertController
Expand Down Expand Up @@ -66,6 +59,7 @@ protected static function commandAliases(): array
'tc',
'td',
],
'yaml2json' => ['yml2json', 'y2j'],
'yaml2prop' => ['yml2prop', 'y2p'],
'prop2yaml' => ['prop2yml', 'p2y'],
];
Expand Down Expand Up @@ -115,91 +109,53 @@ public function sql2mdCommand(FlagsParser $fs, Output $output): void

$md = DBTable::fromSchemeSQL($source)->toMDTable();
$output->writeRaw($md);
// $cm = new CliMarkdown();
// $output->println($cm->parse($md));
}

/**
* convert formatted text to markdown table
*
* @arguments
* type The target text doc type, allow: raw, md-table,
* convert YAML to JSON contents.
*
* @options
* -s,--source string;The source code for convert. allow: FILEPATH, @clipboard;true
* -o,--output The output target. default is stdout.
* --is, --item-sep The item sep char. default is NL.
* --vn, --value-num int;The item value number. default get from first line.
* --vs, --value-sep The item value sep char. default is SPACE
* -s,--source The source code. allow: @i,@c,filepath. if is empty, will try read from STDIN
* -o,--output string;The output target, allow: filepath, clipboard, stdout;;stdout
*
* @param FlagsParser $fs
* @param Output $output
*
* @example
* {binWithCmd} -s @c --vn
*/
public function textCommand(FlagsParser $fs, Output $output): void
public function yaml2jsonCommand(FlagsParser $fs, Output $output): void
{
$text = $fs->getOpt('source');
$text = ContentsAutoReader::readFrom($text);

$p = TextParser::new($text);
$p->setItemSep($fs->getOpt('item-sep'));
$p->setFieldNum($fs->getOpt('value-num'));

if ($vSep = $fs->getOpt('value-sep')) {
$p->setItemParser(TextParser::charSplitParser($vSep));
$str = ContentsAutoReader::readFrom($fs->getOpt('source'));
$data = ConfigUtil::parseYamlString($str);
if (!$data) {
$output->warning('empty data for convert');
return;
}

$p->parse();

switch ($fs->getArg('type')) {
case 'mdtable':
case 'mdTable':
case 'md-table':
$rows = ListStream::new($p->getData())
->eachToArray(function (array $item) {
return implode(' | ', $item);
});
$head = array_shift($rows);
$line = implode('|', array_pad(['-----'], $p->fieldNum, '-----'));

$result = $head . "\n" . $line . "\n". implode("\n", $rows);
break;
case 'raw':
$result = $text;
break;
default:
$result = Json::pretty($p->getData());
break;
$echoTip = true;
$outFile = $fs->getOpt('output');
if (KiteUtil::isStdoutAlias($outFile)) {
$echoTip = false;
$result = JSONPretty::pretty($data);
} else {
$result = Json::pretty($data);
}

$outFile = $fs->getOpt('output');
ContentsAutoWriter::writeTo($outFile, $result);
ContentsAutoWriter::writeTo($outFile, $result, ['printTips' => $echoTip]);
}

/**
* convert YAML to java properties contents.
*
* @options
* -f,--file The source code file. if is empty, will try read from clipboard
* -s,--source The source code. allow: @i,@c,filepath. if is empty, will try read from STDIN
* -o,--output string;The output target, allow: filepath, clipboard, stdout;;stdout
*
* @param FlagsParser $fs
* @param Output $output
*/
public function yaml2propCommand(FlagsParser $fs, Output $output): void
{
$file = $fs->getOpt('file');

$str = ContentsAutoReader::readFrom($file);
if (!$str) {
throw new InvalidArgumentException('the source yaml contents is empty');
}

$parser = new Parser();
/** @var array $data */
$data = $parser->parse(trim($str));
$str = ContentsAutoReader::readFrom($fs->getOpt('source'));
$data = ConfigUtil::parseYamlString($str);
if (!$data) {
$output->warning('empty data for convert');
return;
Expand All @@ -209,40 +165,27 @@ public function yaml2propCommand(FlagsParser $fs, Output $output): void

$result = $jp->encode($data);
$outFile = $fs->getOpt('output');
$echoTip = !KiteUtil::isStdoutAlias($outFile);

ContentsAutoWriter::writeTo($outFile, $result);
$output->success('Complete');
ContentsAutoWriter::writeTo($outFile, $result, ['printTips' => $echoTip]);
}

/**
* convert java properties to YAML contents.
*
* @options
* -f,--file The source code file. if is empty, will try read from clipboard
* -s,--source The source code. allow: @i,@c,filepath. if is empty, will try read from STDIN
* -o,--output string;The output target, allow: filepath, clipboard, stdout;;stdout
*
* @param FlagsParser $fs
* @param Output $output
*/
public function prop2yamlCommand(FlagsParser $fs, Output $output): void
{
$file = $fs->getOpt('file');
if (!$file) {
$str = Clipboard::readAll();
} else {
if (!is_file($file)) {
throw new PromptException("input source file not exists, file: $file");
}

$str = file_get_contents($file);
}

if (!$str) {
throw new InvalidArgumentException('the source properties contents is empty');
}

$str = ContentsAutoReader::readFrom($fs->getOpt('source'));
$prop = new JavaProperties();
$data = $prop->decode($str);

if (!$data) {
$output->warning('empty data for convert');
return;
Expand All @@ -252,17 +195,9 @@ public function prop2yamlCommand(FlagsParser $fs, Output $output): void
$result = $dumper->dump($data, 1, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);

$outFile = $fs->getOpt('output');
if (!$outFile || $outFile === 'stdout') {
$output->println($result);
} elseif ($outFile === 'clipboard') {
$output->info('will send result to Clipboard');
Clipboard::writeString($result);
} else {
$output->info("will write result to $outFile");
File::putContents($outFile, $result);
}
$echoTip = !KiteUtil::isStdoutAlias($outFile);

$output->success('Complete');
ContentsAutoWriter::writeTo($outFile, $result, ['printTips' => $echoTip]);
}

/**
Expand Down
Loading

0 comments on commit 4ca885a

Please sign in to comment.