1

我已将命令的 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
4

1 回答 1

1

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

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

Sample将类方法更改main为以下内容:

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

谢谢你提出这个!我在模块中添加了一个示例Unsorted.java 。picocli-examples

于 2021-02-03T03:09:33.033 回答