首页 > 解决方案 > Picocli:如何始终显示标题/横幅

问题描述

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-linecommand-line-interfacepicocli

解决方案


这有两个方面:

  • 如何从应用程序中获取横幅文本?
  • 如何渲染 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);
  }
}

推荐阅读