【问题标题】:Picocli: how to show header/banner at all timesPicocli:如何始终显示标题/横幅
【发布时间】:2018-10-22 11:25:33
【问题描述】:

Picocli 提供了在@Command 注解中添加漂亮标题的功能,例如:

@Command(name = "git-star", header = {
    "@|green       _ _      _             |@", 
    "@|green  __ _(_) |_ __| |_ __ _ _ _  |@",
    "@|green / _` | |  _(_-<  _/ _` | '_| |@",
    "@|green \\__, |_|\\__/__/\\__\\__,_|_|   |@",
    "@|green |___/                        |@"},
    description = "Shows GitHub stars for a project",
    mixinStandardHelpOptions = true, version = "git-star 0.1")

如何在程序运行时始终显示该标题/横幅,而不在两个地方复制此横幅?

(另见https://github.com/remkop/picocli/issues/517

【问题讨论】:

    标签: command-line command-line-interface picocli


    【解决方案1】:

    这有两个方面:

    • 如何从应用程序中获取横幅文字?
    • 如何渲染 ANSI 颜色和样式?

    您可以使用new CommandLine(new App()).getCommandSpec().usageHelpMessage().header() 或通过在您的应用程序中注入@Spec 带注释的CommandSpec 字段从使用帮助消息中获取横幅。

    要呈现 ANSI 样式,请为每个横幅行使用 CommandLine.Help.Ansi.AUTO.string(line)

    把它们放在一起:

    @Command(name = "git-star", header = {
            "@|green       _ _      _             |@", 
            "@|green  __ _(_) |_ __| |_ __ _ _ _  |@",
            "@|green / _` | |  _(_-<  _/ _` | '_| |@",
            "@|green \\__, |_|\\__/__/\\__\\__,_|_|   |@",
            "@|green |___/                        |@"},
            description = "Shows GitHub stars for a project",
            mixinStandardHelpOptions = true, version = "git-star 0.1")
    class GitStar implements Runnable {
    
      @Option(names = "-c")
      int count;
    
      @Spec CommandSpec spec;
    
      // prints banner every time the command is invoked
      public void run() {
    
        String[] banner = spec.usageHelpMessage().header();
    
        // or: String[] banner = new CommandLine(new GitStar())
        //        .getCommandSpec().usageHelpMessage().header();
    
        for (String line : banner) {
          System.out.println(CommandLine.Help.Ansi.AUTO.string(line));
        }
    
        // business logic here...
      }
    
      public static void main(String[] args) {
        CommandLine.run(new GitStar(), args);
      }
    }
    

    【讨论】:

    • 不能用 3.9.5 编译这个,应该是this.spec.usageMessage().header()
    【解决方案2】:

    对于我在 Picocli 4.5.2 中的工作方式如下:

    public void run() {
        CommandLine cmd = new CommandLine(new App());
        cmd.usage(System.out, Ansi.ON);
    
        // business logic here...
    }
    

    【讨论】:

    • 这也可以,并打印完整的使用帮助消息。如果那是适合应用程序的东西,那当然很好。最初的问题来自应用程序只想打印横幅(没有选项描述),然后是其他一些输出的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    相关资源
    最近更新 更多