在 PicoCli 中自定义帮助显示?

Customized help display in PicoCli?

我有一个用例,我需要 post 指定格式的 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,则不会。

有更好的方法吗?

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

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

Picocli 确实提供了一种通过 Help API. This allows you to reorder or replace sections in the usage help message. I believe the section you want to replace is the command list section 动态自定义使用帮助消息的方法。

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