【问题标题】:PicoCLI : Options order in Usage sectionPicoCLI : 使用部分中的选项顺序
【发布时间】:2021-05-06 07:55:35
【问题描述】:

我已将命令的 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" }, required = true, description = "type")
    String type;

    @Option(names = { "-c" }, required = true, 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

【问题讨论】:

    标签: picocli


    【解决方案1】:

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

    可以自定义概要,但不能使用注释 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

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2023-02-22
      • 1970-01-01
      • 2020-08-23
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      相关资源
      最近更新 更多