PicoCLI:使用部分中的选项顺序

问题描述

我已将命令的 sortOptions 设置为 false,但仍然在“用法”部分中按排序顺序看到命令的选项。 我想按照声明顺序查看它们。

示例代码

@Command(name = "application",subcommands = { AddSubCommand.class })
public class Sample implements Runnable {
    @Spec CommandSpec spec;

    @Override
    public void run() {
        throw new ParameterException(spec.commandLine(),"Specify a subcommand");
    }

    public static void main(String... args) {
        new CommandLine(new Sample()).execute("add","-h");
    }
}

@Command(name = "add",sortOptions = false)
class AddSubCommand implements Runnable {
    @Option(names = { "-h" },usageHelp = true,hidden = true)
    boolean helpFlag;

    @Option(names = { "-i" },required = true,description = "id")
    int id;

    @Option(names = { "-t" },description = "type")
    String type;

    @Option(names = { "-c" },description = "config")
    String config;

    public void run() {
        // logic
    }
}

输出

Usage: application add -c=<config> -i=<id> -t=<type>
  -i=<id>        id
  -t=<type>      type
  -c=<config>    configuration

期待

Usage: application add  -i=<id> -c=<config> -t=<type>
  -i=<id>        id
  -t=<type>      type
  -c=<config>    configuration

解决方法

无论是否指定了 sortOptions = false,选项都在概要行中排序是正确的。 (sortOptions 注释属性仅影响使用帮助消息的 options list 部分的顺序,而不影响概要。)

可以自定义概要,但不能使用注释 API;您将需要使用程序化 API。

Samplemain 方法更改为以下内容:

public static void main(String... args) {
    new CommandLine(new Sample())
            .setHelpFactory(new UnsortedSynopsisHelpFactory())
            .execute("add","-h");
}

并添加以下 UnsortedSynopsisHelpFactory 类:

class UnsortedSynopsisHelpFactory implements CommandLine.IHelpFactory {

    @Override
    public CommandLine.Help create(CommandSpec commandSpec,ColorScheme colorScheme) {
        return new CommandLine.Help(commandSpec,colorScheme) {
            @Override
            protected Ansi.Text createDetailedSynopsisOptionsText(
                    Collection<ArgSpec> done,Comparator<OptionSpec> optionSort,boolean clusterBooleanOptions) {

                return super.createDetailedSynopsisOptionsText(
                        done,null,// do not sort options in synopsis
                        clusterBooleanOptions);
            }
        };
    }
}

这将给出以下输出:

Usage: application add -i=<id> -t=<type> -c=<config>
  -i=<id>        id
  -t=<type>      type
  -c=<config>    config

感谢您提出这个问题!我在 picocli-examples 模块中添加了一个示例 Unsorted.java

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...