【问题标题】:Customized help display in PicoCli?PicoCli 中的自定义帮助显示?
【发布时间】:2019-11-23 03:14:19
【问题描述】:

我有一个用例,我需要以指定格式发布 CLI 的整个帮助。我找到了一种使用以下方法的方法:


@CommandLine.Command(name="myAp",
        synopsisSubcommandLabel = "", usageHelpWidth = 120,
        commandListHeading = "",
        customSynopsis =  "\n\nArguments for MyApp operation.\n"
                + "\n"
                + "Operations:\n"
                + "    create                 Create the stuff\n"
                + "    list                   List the stuff\n"
                + "    add                    Add things\n"
                + "        -r --type                  One or both of [Type1, Typ2]\n"
                + "        -a --annualCost            AnnualCost\n"
                + "        -n --number                Number of each type thing\n"
                + "    subtract               Subtract things\n"
                + "        -r --reasons               Combination of\n"
                + "                                        fiscal (fiscal reason)\n"
                + "                                        operational (operational reason\n"
                + "                                        other (other reason)\n"
                + "    -h      Display this help message and exit\n"
)
class PicoCliParser {
    // All of my other Parameters and options here

    @Option(names = { "-h", "--help" }, usageHelp = true, hidden = true)
    boolean helpRequested = false;

    public static void main(String[] args) throws Exception {
        PicoCliParser parser = new PicoCliParser();
        CommandLine cmd = new CommandLine(parser);
        try {
            CommandLine.ParseResult parseResult = cmd.parseArgs(args);
            System.err.println("parseResults: " + parseResult.matchedArgs().toString());
            if (cmd.isUsageHelpRequested()) {
                cmd.usage(System.out);
            }
        } catch (CommandLine.ParameterException e) {

        }

    }
}

如果用户输入 -h 或 --help,帮助会以我想要的格式打印出来,如果他们不输入 -h 或 -H 则不会。

有没有更好的方法来做到这一点?

如果我们将来添加其他命令,那么添加它们的人必须记住更新帮助字符串。

【问题讨论】:

    标签: command-line-arguments picocli


    【解决方案1】:

    您的解决方案有效,但有一个缺点(如您提到的),使用帮助消息是静态的,不会反映未来的更新,例如新的子命令或添加的选项。

    Picocli 确实提供了一种通过其Help API 动态自定义使用帮助消息的方法。这允许您重新排序或替换使用帮助消息中的部分。我相信您要替换的部分是command list section

    这需要深入了解 picocli 使用帮助模型。为了帮助您入门,picocli-examples 模块提供了一些自定义帮助示例。 This example 显示如何修改使用帮助消息以显示完整的命令层次结构(尽管没有选项),这与您想要做的非常接近。你可以把它作为一个起点。如果您有更多问题,请随时在 picocli github 问题跟踪器(或此处)上提出问题。

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2021-11-27
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多