2

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

4

2 回答 2

2

这有两个方面:

  • 如何从应用程序中获取横幅文本?
  • 如何渲染 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);
  }
}
于 2018-10-22T11:25:33.117 回答
0

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

public void run() {
    CommandLine cmd = new CommandLine(new App());
    cmd.usage(System.out, Ansi.ON);

    // business logic here...
}
于 2021-01-09T23:07:28.983 回答