Skip to content

v4 create group

Inhere edited this page May 28, 2022 · 6 revisions

创建命令组

通过 Controller 形式可以简单快速的组织一组相关命令。

代码示例

先看一个代码示例,来自我的项目 inhere/kite

<?php declare(strict_types=1);

namespace Inhere\Kite\Console\Controller;

use Inhere\Console\Controller;
use Inhere\Console\Exception\PromptException;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
use Inhere\Kite\Console\Component\Clipboard;
use Inhere\Kite\Common\Cmd;
use Inhere\Kite\Common\CmdRunner;
use Inhere\Kite\Helper\AppHelper;
use Inhere\Kite\Helper\GitUtil;
use PhpGit\Changelog\Filter\KeywordsFilter;
use PhpGit\Changelog\Formatter\GithubReleaseFormatter;
use PhpGit\Changelog\Formatter\SimpleFormatter;
use PhpGit\Changelog\GitChangeLog;
use PhpGit\Git;
use PhpGit\Info\TagsInfo;
use PhpGit\Repo;
use Throwable;
use Toolkit\PFlag\FlagsParser;
use Toolkit\Stdlib\Obj\ConfigObject;
use Toolkit\Stdlib\Str;

/**
 * Class GitController
 */
class GitController extends Controller
{
    protected static $name = 'git';

    protected static $description = 'Provide useful tool commands for quick use git';

    /**
     * @var ConfigObject
     */
    private $settings;

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

    protected static function commandAliases(): array
    {
        return [
            'changelog'    => ['chlog', 'clog', 'cl'],
            'log'          => ['l', 'lg'],
        ];
    }

    /**
     * @return string[]
     */
    protected function options(): array
    {
        return [
            '--dry-run' => 'bool;Dry-run the workflow, dont real execute',
            '-y, --yes' => 'Direct execution without confirmation',
            // '-i, --interactive' => 'Run in an interactive environment[TODO]',
        ];
    }

    protected function beforeRun(): void
    {
        if ($this->app && !$this->settings) {
            $this->settings = ConfigObject::new($this->app->getArrayParam('git'));
        }
    }
    
    /**
     * display recently git commits information by `git log`
     *
     * @arguments
     *  maxCommit       int;Max display how many commits;;15
     *
     * @options
     *  --abbrev-commit     bool;Only display the abbrev commit ID
     *  --exclude           Exclude contains given sub-string. multi by comma split.
     *  --file              Export changelog message to file
     *  --format            The git log option `--pretty` value.
     *                      can be one of oneline, short, medium, full, fuller, reference, email, raw, format:<string> and tformat:<string>.
     *  --max-commit        int;Max display how many commits
     *  --no-color          bool;Dont use color render git output
     *  --no-merges         bool;No contains merge request logs
     *
     * @param FlagsParser $fs
     * @param Output $output
     */
    public function logCommand(FlagsParser $fs, Output $output): void
    {
        $b = Git::new()->newCmd('log');

        $noColor = $fs->getOpt('no-color');
        $exclude = $fs->getOpt('exclude');

        $noMerges  = $fs->getOpt('no-merges');
        $abbrevID  = $fs->getOpt('abbrev-commit');
        $maxCommit = $fs->getOpt('max-commit', $fs->getArg('maxCommit'));

        // git log --color --graph --pretty=format:'%Cred%h%Creset:%C(ul yellow)%d%Creset %s (%Cgreen%cr%Creset, %C(bold blue)%an%Creset)' --abbrev-commit -10
        $b->add('--graph');
        $b->addIf('--color', !$noColor);
        $b->add('--pretty=format:"%Cred%h%Creset:%C(ul yellow)%d%Creset %s (%Cgreen%cr%Creset, %C(bold blue)%an%Creset)"');
        $b->addIf("--exclude=$exclude", $exclude);
        $b->addIf('--abbrev-commit', $abbrevID);
        $b->addIf('--no-merges', $noMerges);
        $b->add('-' . abs($maxCommit));

        $b->runAndPrint();

        $output->success('Complete');
    }
}

TIP: 创建好命令后需要注册到 Application 才能运行, 请看 注册命令 章节

绑定选项参数

可以观察到上面 logCommand 示例的注释是有一定格式的。

    /**
     * display recently git commits information by `git log`
     *
     * @arguments
     *  maxCommit       int;Max display how many commits;;15
     *
     * @options
     *  --abbrev-commit     bool;Only display the abbrev commit ID
     *  --exclude           Exclude contains given sub-string. multi by comma split.
     *  --file              Export changelog message to file
     *  --format            The git log option `--pretty` value.
     *                      can be one of oneline, short, medium, full, fuller, reference, email, raw, format:<string> and tformat:<string>.
     *  --max-commit        int;Max display how many commits
     *  --no-color          bool;Dont use color render git output
     *  --no-merges         bool;No contains merge request logs
     *
     * @param FlagsParser $fs
     * @param Output $output
     */

跟独立命令一样,命令组里的子命令也可以通过方法注释快速绑定命令选项和参数,运行时console会自动解析并绑定到当前命令

  • @arguments 后面的即是命令参数
  • @options 后面的即是命令选项
    • 注意选项名和后面的设置描述需间隔一定距离
    • 规则以分号 ; 分割每个部分 (完整规则:type;desc;required;default;shorts)
    • 默认是 string 类型,可以忽略

选项参数解析使用的 php-toolkit/pflag 更多说明可以点击查看

查看帮助

我们可以使用 -h 选项查看添加选项后效果

执行 ./bin/myapp.php git log -h:

image

运行命令

运行 ENTRY git log 即会调用 GitController::logCommand():

./bin/myapp.php git log
# 添加选项和参数
./bin/myapp.php git log 2
./bin/myapp.php git log --abbrev-commit 5

注意运行命令应当遵循通用的Linux命令调用格式:ENTRY CMD --OPTIONS ARGUMENTS

运行效果:

image